Swift Dictionary default value

前端 未结 3 1350
走了就别回头了
走了就别回头了 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:15

    Using Swift 2 you can achieve something similar to python's version with an extension of Dictionary:

    // Values which can provide a default instance
    protocol Initializable {
        init()
    }
    
    extension Dictionary where Value: Initializable {
        // using key as external name to make it unambiguous from the standard subscript
        subscript(key key: Key) -> Value {
            mutating get { return self[key, or: Value()] }
            set { self[key] = newValue }
        }
    }
    
    // this can also be used in Swift 1.x
    extension Dictionary {
        subscript(key: Key, or def: Value) -> Value {
            mutating get {
                return self[key] ?? {
                    // assign default value if self[key] is nil
                    self[key] = def
                    return def
                }()
            }
            set { self[key] = newValue }
        }
    }
    

    The closure after the ?? is used for classes since they don't propagate their value mutation (only "pointer mutation"; reference types).

    The dictionaries have to be mutable (var) in order to use those subscripts:

    // Make Int Initializable. Int() == 0
    extension Int: Initializable {}
    
    var dict = [Int: Int]()
    dict[1, or: 0]++
    dict[key: 2]++
    
    // if Value is not Initializable
    var dict = [Int: Double]()
    dict[1, or: 0.0]
    

提交回复
热议问题