Page 47
infix operator ?? { associativity right precedence 110 }
func ??<T>(optional: T?, defaultValue: T) -> T {
if let x = optional {
return x
} else {
return defaultValue
}
}
上面实现了操作符 ?? 但书中指出存在一个问题:
There is one problem with this definition: the defaultValue may be evaluated, regardless of whether or not the optional is nil. This is usually undesirable behavior: an if-then-else statement should only execute one of its branches, depending on whether or not the associated condition is true. Similarly, the ?? operator should only evaluate the defaultValue argument when the optional argument is nil. As an illustration, suppose we were to call ??, as follows:
optional ?? defaultValue
In this example, we really do not want to evaluate defaultValue if the optional variable is non-nil — it could be a very expensive computation that we only want to run if it is absolutely necessary.
最后swift库中正确的实现是这样的:
func ??<T>(optional: T?, defaultValue: @autoclosure () -> T) -> T {
if let x = optional {
return x
} else {
return defaultValue()
}
}
请问 the defaultValue may be evaluated, regardless of whether or not the optional is nil 为什么会存在这个问题呢
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.