2014-09-23 2 views
1

Swift에서 매개 변수로 문자열 사전을 사용하고 문자열 튜플을 반환하는 함수를 만들려고합니다. 내가 반환하는 튜플의 값 중 하나가 "nil"인 경우 내 프로그램을 중단시키지 않기 때문에 사전에 키, 값 쌍을 옵션으로 사용하고 싶습니다.어떻게 문자열 옵션을 신속하게 "해시 가능"하게 만드나요?

func songBreakdown(song songfacts: [String?: String?]) -> (String, String, String) { 
return (songfacts["title"], songfacts["artist"], songfacts["album"]) 
} 
if let song = songBreakdown(song: ["title": "The Miracle", 
           "artist": "U2", 
           "album": "Songs of Innocence"]) { 
println(song); 
} 

말한다 첫 번째 줄에 오류 메시지가 :. "유형 해쉬를 ''? 문자열 프로토콜을 준수하지 않는이 '

I 키를 만드는 시도, 매개 변수에 대한 값 쌍되지 선택적 항목 ...

그러나 다음과 같은 오류 메시지가 표시됩니다. "조건부 바인딩의 바인딩 된 값은 선택적 유형이어야합니다. 이 문제를 어떻게 해결할 수 있습니까?

답변

1

이미 알고 있듯이 옵션 키를 사전의 키로 사용할 수 없습니다. 따라서 두 번째 시도에서 시작하여 함수에 의해 반환 된 값은 선택적 튜플이 아닌 optionals의 튜플이므로 오류가 발생합니다. 대신, 함수에 의해 반환 된 값을 푸는 변수에 할당하고 각 구성 요소의 포장을 푸는 노력의 :

func songBreak(song songfacts: [String: String]) -> (String?, String?, String?) { 
    return (songfacts["title"], songfacts["artist"], songfacts["album"]) 
} 

let song = songBreak(song: ["title": "The Miracle", "artist": "U2", "album": "Songs of Innocence"]) 

if let title = song.0 { 
    println("Title: \(title)") 
} 
if let artist = song.1 { 
    println("Artist: \(artist)") 
} 
if let album = song.2 { 
    println("Album: \(album)") 
} 

롭 Mayoff이 코멘트에 제안한 것처럼를, 그것은 튜플 요소의 이름을 더 나은 스타일은 다음과 같습니다

func songBreak(song songfacts: [String: String]) -> (title: String?, artist: String?, album: String?) { 
    return (title: songfacts["title"], artist: songfacts["artist"], album: songfacts["album"]) 
} 

let song = songBreak(song: ["title": "The Miracle", "artist": "U2", "album": "Songs of Innocence"]) 

if let title = song.title { 
    println("Title: \(title)") 
} 
if let artist = song.artist { 
    println("Artist: \(artist)") 
} 
if let album = song.album { 
    println("Album: \(album)") 
} 
+2

더 나은 스타일 : 튜플 요소의 이름을 지정하십시오. 'func songBreak (song songfacts : [String : String]) -> (title : String ?, artist : String ?, album : String?)'...'let title = song.title' –

+1

고마워 Rob, 훌륭한 제안. – vacawama

관련 문제