Swift Dictionary default value

前端 未结 3 1351
走了就别回头了
走了就别回头了 2020-12-06 18:31

A pattern I\'ve gotten used to with Python\'s defaultdicts is a dictionary that returns a default value if the value for a given key has not been explicitly set. Trying to d

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-06 19:29

    This changed in Swift 4, and there's now a way to read a key's value or provide a default value if the key isn't present. For example:

    let person = ["name": "Taylor", "city": "Nashville"]
    let name = person["name", default: "Anonymous"]
    

    This is particularly useful when modifying dictionary values, because you can write code like this:

    var favoriteTVShows = ["Red Dwarf", "Blackadder", "Fawlty Towers", "Red Dwarf"]
    var favoriteCounts = [String: Int]()
    
    for show in favoriteTVShows {
        favoriteCounts[show, default: 0] += 1
    }
    

    I covered this change and others in my article What's new in Swift 4.

提交回复
热议问题