ref – http://stackoverflow.com/questions/39560860/uiview-cmdevicemotionhandler-unowned-may-only-be-applied-to-class-and-class-b
The line of code you’re on is actually run during the init function. self is not available until after all stored properties are initialized. You’re in the middle of the process.
The closure businessCardName we’re defining is in the middle of the init process, and thus, do not exist yet.
Solution:
Declare it indeed as lazy var instead of let, so the code is not run during init but in fact at first use.
Closure Solution
1 2 3 4 5 6 7 8 |
// this is a closure, thus we need to define self in the params list to be used // (parameter) -> (return type) = { // closure definition } lazy var businessCardName : () -> String = { [unowned self] in // only calls this once print("------ \(#function) -------") return "Mr. Kraken AKA " + self.petName } |
used like this:
1 |
let answer = kraken?.businessCardName() |
its a closure, so to use it, we have to use the parentheses.
Using Anonymous Functions (also closures)
You can also use anonymous functions, execute it by using “()”, then assign the result back to variable.
1 2 3 4 5 |
// lazy means this is defined only after the init process, and during its first use lazy var businessCardName : String = { print("----- \(#function) ------") return "Mr. Kraken AKA " + self.petName }() |
used like this:
1 |
let answer = kraken?.businessCardName |