[英]How do you make string optionals in swift “hashable”?
I am trying to make a function in Swift, that takes a dictionary of strings as a parameter, and returns a tuple of strings. 我正在尝试在Swift中创建一个函数,该函数将字符串字典作为参数,并返回字符串元组。 I want the key, value pairs in the dictionary to be optionals, because I don't want my program to crash if one of the values in the tuple it returns is "nil".
我希望字典中的键,值对是可选的,因为如果它返回的元组中的值之一为“ 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);
}
There is an error message on the first line that says: "Type 'String? does not conform to protocol 'Hashable'. 第一行上有一条错误消息,内容为:“类型'String?不符合协议'Hashable'。
I tried making the key, value pair for the parameter not optionals... 我尝试制作参数的键,值对不是可选的...
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);
}
But then there is an error message that says: "The bound value in conditional binding must be of optional type. How can I fix this? 但是,然后出现一条错误消息:“条件绑定中的绑定值必须是可选类型。如何解决此问题?
As you already figured out, you can't use optionals as the keys of a dictionary. 正如您已经知道的那样,您不能将可选键用作字典的键。 So, starting with your second attempt, you are getting the error because the value returned by your function is a tuple of optionals, not an optional tuple.
因此,从第二次尝试开始,您会收到错误消息,因为函数返回的值是可选的元组,而不是可选的元组。 Instead of trying to unwrap the value returned by the function, assign it to a variable and then unwrap each component:
与其尝试解开函数返回的值,不如将其分配给变量,然后解开每个组件:
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)")
}
As Rob Mayoff suggested in the comments, it is better style to name the tuple elements: 正如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)")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.