skip to Main Content

<I realize similar questions have already been asked, but they have very complex questions or insufficient answers (I’m a beginner with swift)>

I’ve included a very basic example that summarizes my issue

struct Greeting {

    var name = "Bob"
  
    var message = "Hi, " + name
}

var a = Test("John")
print(a.message)

I get the following error:

error: cannot use instance member ‘name’ within property initializer; property initializers run before ‘self’ is available

I’ve tried initializing the values, creating my best guess at lazy vars, and making the vars computed values. Any help would be appreciated!

2

Answers


  1. You are using name before the struct is initialized. If you make message a computed properties it should work.

    struct Greeting {
        var name = "Bob"
    
        var message: String {
            "Hi, " + name
        }
    }
    
    Login or Signup to reply.
  2. You are getting the error because in Swift you need to give variables some value before you can use them.

       struct Greeting {
            var name = "Bob"      // <-- this variable is initialized with "Bob"
            var message: String   // <-- this var is not, you need to initialize it yourself
                                 // which means you cannot use this before you give it a value
            
            // a very common approach is to have your own initializer function init.
            init(name: String, message: String) {
                self.name = name    // <-- this is initialized (again in our case)
                self.message = "Hi " + name  // this is now initialized the way you want it
            }
    
           // you can have many customized init, like this
           init() {
              // here because name is already initialized with Bob, it's ok
              self.message = "Hi " + name
           }
            
            // if you don't have a init function, swift creates a basic one (or more) for you
            // but it will not be the special one you wanted, like above.
        }
    

    So when Greeting is created the init function is called first. That is the place where you can customize the creation of Greeting. Before that you cannot use the variable "name" as you do in "var message = "Hi, " + name".

    You can use it like this:

            let greet = Greeting()
            print(greet.message)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search