【问题标题】:How do you make string optionals in swift "hashable"?你如何在快速的“哈希”中制作字符串选项?
【发布时间】:2014-09-23 12:23:42
【问题描述】:

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

然后有一条错误消息说:“条件绑定中的绑定值必须是可选类型。我该如何解决这个问题?

【问题讨论】:

    标签: function swift optional


    【解决方案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 在 cmets 中建议的那样,命名元组元素的风格更好:

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

    【讨论】:

    • 更好的风格:命名元组元素。 func songBreak(song songfacts: [String: String]) -> (title: String?, artist: String?, album: String?) ... if let title = song.title
    猜你喜欢
    • 2014-03-26
    • 2012-03-21
    • 1970-01-01
    • 1970-01-01
    • 2016-01-02
    • 2017-12-21
    • 2019-08-02
    • 1970-01-01
    • 2018-11-08
    相关资源
    最近更新 更多