Assign value to optional dictionary in Swift

后端 未结 4 1192
北恋
北恋 2020-12-10 04:42

I\'m finding some surprising behavior with optional dictionaries in Swift.

var foo:Dictionary?

if (foo == nil) {
    foo = [\"bar\": \         


        
4条回答
  •  渐次进展
    2020-12-10 05:40

    This is because your Dictionary is optional. If it's nil, you won't add an entry to it.

    You can do this way:

    var dict: [String : String]?
    if let dict = dict {
      dict["key"] = "value" // add a value to an existing dictionary
    } else {
      dict = ["key" : "value"] // create a dictionary with this value in it
    }
    

    Or, if you are given an optional dictionary, for example HTTPHeaders - which in AlamoFire is a [String : String] dictionary - and you want to either add a value if it's non-nil, or create it with this value if it's nil, you could do like so:

    let headers: HTTPHeaders? // this is an input parameter in a function for example
    
    var customHeaders: HTTPHeaders = headers ?? [:] // nil coalescing
    customHeaders["key"] = "value"
    

提交回复
热议问题