I have the following struct:
struct Person {
let name: String
let age: Int
let assets: Double
}
To initialize a person, I would like to pass it a dictionary that contains the name and age, as well as info to calculate the assets:
public init(info: [String : AnyObject]) {
if let name = info["name"] as? String {
self.name = name
}
if let age = info["age"] as? Int {
self.age = age
}
if let assets = info["assets"] as? [String : AnyObject] {
calculateAssets(assets: assets)
}
}
mutating func calculateAssets(assets: [String : AnyObject]) {
self.assets = 1+2+3.4 // really do this with info from the dictionary
}
With this setup, I get two compiler errors:
- 'self' used before all stored properties are initialized
- Return from initializer without initializing all stored properties
Following the compiler suggestions, I added a default value for each property, and changed them to be a var:
struct Person {
var name: String = ""
var age: Int = 0
var assets: Double = 0.0
// init ...
}
And indeed, the compiler errors are gone.
But am I on the right track by making these corrections?