How to convert NSNull to nil in Swift?

前端 未结 2 1154
后悔当初
后悔当初 2020-12-17 15:13

I want to fetch JSON data from my server and manipulate it upon launch. In Objective-C, I have used this #define code to convert NSNull to ni

相关标签:
2条回答
  • 2020-12-17 15:29

    This could be what you are looking for:

    func nullToNil(value : Any?) -> Any? {
        if value is NSNull {
            return nil
        } else {
            return value
        }
    }
    
    people.age = nullToNil(peopleDict["age"])
    
    0 讨论(0)
  • 2020-12-17 15:50

    I would recommend, instead of using a custom conversion function, just to cast the value using as?:

    people.age = peopleDict["age"] as? Int
    

    If the value is NSNull, the as? cast will fail and return nil.

    0 讨论(0)
提交回复
热议问题