I have defined a protocol with a method to return a tuple:
protocol SMCalculatorDelegate {
func numbersToAdd() -> (Int, Int)
}
When i try to call this against the delegate method in my class like this:
class SMCalculator: NSObject {
var delegate : SMCalculatorDelegate?
func add() {
let myTuple : (n1: Int, n2: Int) = delegate?.numbersToAdd()
}
}
I get the following error on the line starting let myTuple...
referring to the .numbersToAdd()
section of that line of code.
"Value of optional type '(Int, Int)?' not unwrapped; did you mean to use '!' or '?'?"
Why doesn't this work when I can extract the tuple without error like this?
let tuple = delegate?.numbersToAdd()
println(tuple) //Prints (5,5)
I'm still trying to get grips with everything, but it seems like correct behaviour.
Should delegate
be nil, you would assign nil to myTuple, thus you need to make myTuple optional as well...
class SMCalculator: NSObject {
var delegate : SMCalculatorDelegate?
func add() {
let myTuple : (n1: Int, n2: Int)? = delegate?.numbersToAdd()
// this works, because we're saying that myTuple definitely isn't nil
println(myTuple!.n1)
// this works because we check the optional value
if let n1 = myTuple?.n1 {
println(n1)
} else {
println("damn, it's nil!")
}
// doesn't work because you're trying to access the value of an optional structure
println(myTuple.n1)
}
}
works for me
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With