저는 초보자이기 때문에 이것은 초보자 용 질문입니다. 잠재적 인 오류를 발견 한 Swift 3.0 설명서를 숙고했습니다. 예제가 올바르지 않거나 (모호한 경우) 아니면 실제로 일부 가이드 라인을 놓치고 있는지 궁금합니다.Swift 3.0 Optional Chaining
http://swiftdoc.org/v3.0/type/Optional/ 선택 체인에 관한 섹션을 참조하십시오.
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
랩을 해제하고 Optional.some(wrapped)
에 hasSuffix()
만 imagePaths["star"]
경우 결과를 실행하도록되어있다. 이는 isPNG
이 true
또는 false
중 하나임을 의미합니다. 따라서 위 샘플의 함축적 의미는 올바르지 않은데, 이것이 안전하게 언랩하면 값은 항상 true라는 암묵적인 주장이 제기됩니다.
는 여기에 대해 이야기하고 무엇을 설명하는 몇 가지 예입니다 : SwiftDoc.org이 특정 예제를 변경해야하는 경우 내 현재의 분석이 잘못된 경우 또는 단순히 궁금
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"
.
나는 동의한다. 설명서가 잘못되었습니다. 올바른 버전의 예제는 if isPNG = imagePaths [ "star"] ?. hasSuffix (".png") 여기서 isPNG {...}'또는'imagePaths [ "star"] ?. hasSuffix (" .png ") == true {...}'. 그러나 그들의 예는 올바르지 않습니다. – Rob
...또는 좀더 설명 적으로 :'let img = imagePaths [ "star"] img.hasSuffix (".png") {...}'. – dfri
이 예제는 실제로 Apple의 문서 https://developer.apple.com/reference/swift/optional (https://github.com/apple/swift/blob/master/stdlib/ public /core/Optional에서 생성)에서 유래했습니다. 신속한), 누군가가 버그 리포트를 제출해야합니다. –