2

What is the reason I can't give a value to a stored property that depends on the value of another one in Swift 2.0?

The code below gives an error saying:

Something.Type does not have a member named 'foo'

class Something {
    let foo = "bar"
    let baz = "\(foo) baz"
}

This is odd, as Something.Type certainly does have a member called foo.

Is there a way around this?

cfischer
  • 24,452
  • 37
  • 131
  • 214
  • 3
    Compare http://stackoverflow.com/questions/25854300/how-to-initialize-properties-that-depend-on-each-other, http://stackoverflow.com/questions/25855137/viewcontroller-type-does-not-have-a-member-named, http://stackoverflow.com/questions/25582853/type-does-not-have-a-member. – Martin R Aug 06 '15 at 15:03
  • the 'reason' is that the instance has not been initialized yet, and so you cannot refer to its members - see @MartinR's comment for a handful of ways to address this constraint – fqdn Aug 07 '15 at 02:33

2 Answers2

4

Looks like you're trying to initialise the variable baz, before swift has had a chance to know that foo is a property of Something. Place your initialisation inside the init constructor.

class Something {
    let foo: String
    let baz: String

    init () {
        foo = "bar"
        baz = "\(foo) baz"
    }
}
Mark
  • 12,359
  • 5
  • 21
  • 37
2

You can also use lazy initialization but now you have to make it a variable:

class Something {
    let foo = "bar"
    lazy var baz = { "\(self.foo) baz" }()
}
Qbyte
  • 12,753
  • 4
  • 41
  • 57