<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
You are using
name
before the struct is initialized. If you make message a computed properties it should work.You are getting the error because in Swift you need to give variables some value before you can use them.
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: