【发布时间】:2016-11-17 02:28:50
【问题描述】:
我是 swift 新手,所以这绝对是一个新手级别的问题。我在思考一些 Swift 3.0 文档时发现了一个潜在的错误。我想知道这个例子是否不正确(或模棱两可),或者我实际上错过了一些指导方针。
请参阅http://swiftdoc.org/v3.0/type/Optional/ 关于可选链接的部分。
可选链
要安全地访问包装实例的属性和方法,请使用后缀可选链接运算符 (
?)。以下示例使用可选链接访问String?实例上的hasSuffix(_:)方法。if let isPNG = imagePaths["star"]?.hasSuffix(".png") { print("The star image is in PNG format") } // Prints "The star image is in PNG format"
AFAIU,imagePaths["star"]?.hasSuffix(".png") 仅在imagePaths["star"] 导致Optional.some(wrapped) 时才应该安全地打开imagePaths 并运行hasSuffix()。这意味着isPNG 将是true 或false。因此,上述示例的含义是不正确的,因为它隐含地声称如果 this 安全地展开,则该值始终为 true。
这里有一些例子来解释我在说什么:
if let isPNG = imagePaths["star"]?.hasSuffix(".png") {
print("The star has png format")
} else {
print("The star does not have png format")
}
if let isPNG = imagePaths["portrait"]?.hasSuffix(".png") {
print("The portrait has png format")
} else {
print("The portrait does not have png format")
}
// "The portrait has png format\n"
if let isPNG = imagePaths["alpha"]?.hasSuffix(".png") {
print("The alpha has png format")
} else {
print("The alpha does not have png format")
}
// "The alpha does not have png format\n"
我只是想知道我当前的分析是否有误,或者 SwiftDoc.org 是否需要更改此特定示例。
【问题讨论】:
-
我同意。文档不正确。该示例的正确版本是
if let isPNG = imagePaths["star"]?.hasSuffix(".png") where isPNG { ... }或if imagePaths["star"]?.hasSuffix(".png") == true { ... }。但他们的例子是不正确的。 -
... 或者更具描述性:
if let img = imagePaths["star"] where img.hasSuffix(".png") { ... }. -
该示例实际上源自 Apple 的文档 developer.apple.com/reference/swift/optional(生成自 github.com/apple/swift/blob/master/stdlib/public/core/…),因此应该有人提交错误报告。
标签: swift