I am new to Swift and would like to initialize an object\'s member variable using an instance method like this:
class MyClass {
var x: String
var y: Stri
In Swift 3, I've been using this pattern,
class MyClass {
var x: String?
private(set) lazy var y: String? = self.createY()
init(x: String){ self.x = x }
private func createY() -> String?
{
return "\(x ?? "nil") test"
}
}
The secret sauce here is the use of private(set) lazy. This way, you can label your property a var. And lazy will delay initialization until after your init function has completed. Using private(set) only allows the functions inside this class to modify that property, including the lazy keyword, but not let public interfaces change it. Of course, if you want your interface to change your property, then you can also mark it internal (the default) or public. But you need to leave it marked a lazy var