我试图在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);
}
第一行上有一条错误消息:“类型'字符串?不符合协议'Hashable'。
我尝试为参数而不是选项...
创建键值对func songBreak(song songfacts: [String: String]) -> (String?, String?, String?) {
return (songfacts["title"], songfacts["artist"], songfacts["album"])
}
if let song = songBreak(song: ["title": "The Miracle", "artist": "U2", "album": "Songs of Innocence"]) {
println(song);
}
但是有一条错误消息说:“条件绑定中的绑定值必须是可选类型。我该如何解决这个问题?
答案 0 :(得分:1)
正如您已经想到的那样,您不能使用选项作为字典的键。所以,从你的第二次尝试开始, 你得到错误,因为你的函数返回的值是一个选项元组,而不是一个可选的元组。而不是尝试解包函数返回的值,将其分配给变量,然后打开每个组件:
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)")
}
正如Rob 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)")
}