How to add nil value to Swift Dictionary?

前端 未结 9 491
春和景丽
春和景丽 2021-01-31 01:20

I have made a request to my server in my app. And posted data something like this.Server side is waiting for all parameters even they are nil. But i couldn\'t add nil values to

9条回答
  •  佛祖请我去吃肉
    2021-01-31 01:43

    To add a nil value to a dictionary in Swift, your dictionary's values must be of the Optional type.

    Consider a Person class:

    class Person {
        let name: String
        weak var spouse: Person?
    
        init(name: String, spouse: Person?) {
            self.name = name
            self.spouse = spouse
        }
    }
    

    Instances of the Person type can have a name and an optional spouse. Create two instances, and add the first to a dictionary:

    let p1 = Person(name: "John", spouse: nil)
    let p2 = Person(name: "Doe", spouse: p1)
    p1.spouse = p2
    var people = [p1.name: p1.spouse]
    

    This dictionary (called people) maps names to spouses, and is of type [String: Person?]. You now have a dictionary with a value of Optional type: Person?.

    To update the value of the key p1.name to be nil, use the updateValue(_: forKey:) method on the Dictionary type.

    people.updateValue(nil, forKey: p1.name)
    people[p1.name] 
    

    The value for the key p1.name is now nil. Using updateValue(_: forKey:) is a bit more straightforward in this case because it doesn't involve making a throwaway instance, setting it to nil, and assigning that instance to a key in a dictionary.

    NB: See rintaro's answer for inserting null into a post's dictionary.

提交回复
热议问题