gpt4 book ai didi

ios - 从委托(delegate)返回元组(可选类型的值未展开)

转载 作者:搜寻专家 更新时间:2023-10-30 22:14:31 24 4
gpt4 key购买 nike

我已经定义了一个带有返回元组方法的协议(protocol):

protocol SMCalculatorDelegate {

func numbersToAdd() -> (Int, Int)

}

当我尝试像这样针对我的类中的委托(delegate)方法调用它时:

class SMCalculator: NSObject {

var delegate : SMCalculatorDelegate?

func add() {

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

}

}

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

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

当我可以像这样毫无错误地提取元组时,为什么这不起作用?

let tuple = delegate?.numbersToAdd()

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

最佳答案

我仍在努力掌握一切,但这似乎是正确的行为。

如果 delegate 为 nil,您会将 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)

}

}

对我有用

关于ios - 从委托(delegate)返回元组(可选类型的值未展开),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24070815/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com