Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning Tuple From Delegate (Value of optional type not unwrapped)

Tags:

ios

swift

tuples

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)
like image 567
Sammio2 Avatar asked Jun 05 '14 21:06

Sammio2


1 Answers

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

like image 107
Jann Avatar answered Oct 16 '22 08:10

Jann