作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我已经定义了一个带有返回元组方法的协议(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/
我正在尝试用 Swift 编写这段 JavaScript 代码:k_combinations 到目前为止,我在 Swift 中有这个: import Foundation import Cocoa e
我是一名优秀的程序员,十分优秀!