Returning a tuple from a delegate (value of an optional type, not expanded)

I 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 as follows:

 class SMCalculator: NSObject { var delegate : SMCalculatorDelegate? func add() { let myTuple : (n1: Int, n2: Int) = delegate?.numbersToAdd() } } 

I get the following error on a line starting let myTuple... , referring to the .numbersToAdd() section of this line of code.

 "Value of optional type '(Int, Int)?' not unwrapped; did you mean to use '!' or '?'?" 

Why does this not work when I can retrieve a tuple without errors?

 let tuple = delegate?.numbersToAdd() println(tuple) //Prints (5,5) 
+6
source share
1 answer

I'm still trying to handle everything, but it seems like the right behavior.

If the delegate is nil, you must assign nil myTuple, so you need to also make myTuple optional ...

 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 nil!") } // doesn't work because you're trying to access the value of an optional structure println(myTuple.n1) } } 

works for me

+4
source

Source: https://habr.com/ru/post/970414/


All Articles