2016-07-14 7 views
4

저는 초보자이기 때문에 이것은 초보자 용 질문입니다. 잠재적 인 오류를 발견 한 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"] 경우 결과를 실행하도록되어있다. 이는 isPNGtrue 또는 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" 

.

+2

나는 동의한다. 설명서가 잘못되었습니다. 올바른 버전의 예제는 if isPNG = imagePaths [ "star"] ?. hasSuffix (".png") 여기서 isPNG {...}'또는'imagePaths [ "star"] ?. hasSuffix (" .png ") == true {...}'. 그러나 그들의 예는 올바르지 않습니다. – Rob

+3

...또는 좀더 설명 적으로 :'let img = imagePaths [ "star"] img.hasSuffix (".png") {...}'. – dfri

+0

이 예제는 실제로 Apple의 문서 https://developer.apple.com/reference/swift/optional (https://github.com/apple/swift/blob/master/stdlib/ public /core/Optional에서 생성)에서 유래했습니다. 신속한), 누군가가 버그 리포트를 제출해야합니다. –

답변

5

귀하의 분석은 정확하고 SwiftDoc.org의 예는 다음 코드와 같이 오해의 소지가 적어도 입니다 :

imagePaths["star"]?.hasSuffix(".png") 

nil없는 경우

let imagePaths = ["star": "image1.tiff"] 

if let isPNG = imagePaths["star"]?.hasSuffix(".png") { 
    print("The star has png format") 
} else { 
    print("The star does not have png format") 
} 

// Output: The star has png format 

선택적 바인딩 성공 , 즉 선택 체인이 실행될 수 있다면 즉 imagePaths["star"] != nil 인 경우입니다.

모든 상황이 다양한 방법 (무풍 병합 사업자, 패턴 매칭, ...)에서 간단하게 할 수 물론

if let isPNG = imagePaths["star"]?.hasSuffix(".png") { 
    if isPNG { 
     print("The star has png format") 
    } else { 
     print("The star does not have png format") 
    } 
} else { 
    print("No path in dictionary") 
} 

을 것을 테스트하기위한 올바른 방법. 예를 들어

switch(imagePaths["star"]?.hasSuffix(".png")) { 
case true?: 
    print("The star has png format") 
case false?: 
    print("The star does not have png format") 
case nil: 
    print("No path in dictionary") 
} 

또는

let isPNG = imagePaths["star"]?.hasSuffix(".png") ?? false 

(질문에 대한 코멘트에 더 많은 예.)

+0

그것은 지금 많은 의미가 있습니다. 마지막 코드는 내가 결국 생각해내는 코드입니다. 감사. – p0lAris

-3

나는 당신이 Bool과 Optional을 융합하고 있다고 생각합니다. 어떤 경우에는 nil이 false와 같은 역할을하지만 그들은 동일하지 않습니다.

+0

"SwiftDoc.org"의 예제를 해석하고 위에 게시 한 다른 예제를 만들려고했습니다. 나는 내가 만든 예제가 타당하다는 확신을 가지고있다. 그래서 그것은 원래의 예제 자체에 대한 문제와 그것이 암시하려고 시도하는 것과 같습니다. – p0lAris

관련 문제