gpt4 book ai didi

function - 你如何在 swift "hashable"中制作字符串选项?

转载 作者:行者123 更新时间:2023-11-28 07:16:12 28 4
gpt4 key购买 nike

我正在尝试在 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);
}

第一行有一条错误消息:“Type 'String? does not conform to protocol '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);
}

但是随后出现一条错误消息:“条件绑定(bind)中的绑定(bind)值必须是可选类型。我该如何解决这个问题?

最佳答案

如您所知,您不能将可选值用作字典的键。所以,从你的第二次尝试开始,您收到错误是因为您的函数返回的值是可选元组,而不是可选元组。与其尝试解包函数返回的值,不如将其分配给一个变量,然后解包每个组件:

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)")
}

关于function - 你如何在 swift "hashable"中制作字符串选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25986295/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com