Swift 可选链是从左到右延迟评估的吗?
Is Swift optional chaining lazily evaluated left-to-right?
文档似乎没有提及任何关于可选链评估顺序的明确内容,只是:
Multiple queries can be chained together, and the entire chain fails gracefully if any link in the chain is nil.
可能看起来很明显,但我需要确认到底发生了什么,并认为这可能对其他人有帮助。例如我们能安全地做这种事吗?
opVar?.someObject.someMethod(opVar!)
可选链按照您的预期从左到右延迟求值。链中第一个失败的可选停止对该链的任何进一步评估。
// Playground test for left-to-right lazy evaluation.
struct C {
static var i = 0
func chain(count: Int) -> C? {
print("Expected \(count) -> \(C.i)")
assert(count == C.i)
C.i += 1
return C.i > 2 ? nil : self
}
}
let c = C()
c.chain(0)?.chain(1)?.chain(2)?.chain(3)!.chain(4)!
输出
Expected 0 -> 0
Expected 1 -> 1
Expected 2 -> 2
文档似乎没有提及任何关于可选链评估顺序的明确内容,只是:
Multiple queries can be chained together, and the entire chain fails gracefully if any link in the chain is nil.
可能看起来很明显,但我需要确认到底发生了什么,并认为这可能对其他人有帮助。例如我们能安全地做这种事吗?
opVar?.someObject.someMethod(opVar!)
可选链按照您的预期从左到右延迟求值。链中第一个失败的可选停止对该链的任何进一步评估。
// Playground test for left-to-right lazy evaluation.
struct C {
static var i = 0
func chain(count: Int) -> C? {
print("Expected \(count) -> \(C.i)")
assert(count == C.i)
C.i += 1
return C.i > 2 ? nil : self
}
}
let c = C()
c.chain(0)?.chain(1)?.chain(2)?.chain(3)!.chain(4)!
输出
Expected 0 -> 0
Expected 1 -> 1
Expected 2 -> 2