从委托返回元组(未解包的可选类型的值)

时间:2014-06-05 21:53:26

标签: ios tuples swift

我已经使用返回元组的方法定义了一个协议:

protocol SMCalculatorDelegate {

    func numbersToAdd() -> (Int, Int)

}

当我尝试在我的类中对照委托方法调用时,这样:

class SMCalculator: NSObject {

    var delegate : SMCalculatorDelegate?

    func add() {

        let myTuple : (n1: Int, n2: Int) = delegate?.numbersToAdd()

    }

}

我在开始let myTuple...的行上收到以下错误,引用该行代码的.numbersToAdd()部分。

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

为什么当我能像这样没有错误地提取元组时这不起作用?

let tuple = delegate?.numbersToAdd()

println(tuple) //Prints (5,5)

1 个答案:

答案 0 :(得分:4)

我仍然试图掌握一切,但这似乎是正确的行为。

如果delegate为零,你会将nil分配给myTuple,因此你需要将myTuple设为可选...

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)

   } 

}

适合我