Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert NSNull to nil in Swift?

Tags:

swift

xcode6

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 nil, since the fetched data might include null at times.

#define NULL_TO_NIL(obj) ({ __typeof__ (obj) __obj = (obj); __obj == [NSNull null] ? nil : obj; })

However, in Swift, is it possible to convert the NSNull to nil? I want to use the following operation (the code is Objective-C's):

people.age = NULL_TO_NIL(peopleDict["age"]);

In the above code, when the fetched data's age key is NULL, then the people object's .age property is set to nil.

I use Xcode 6 Beta 6.

like image 371
Blaszard Avatar asked Aug 29 '14 19:08

Blaszard


People also ask

What is NSNull in Swift?

A singleton object used to represent null values in collection objects that don't allow nil values.

IS NULL same as nil?

NULL and nil are equal to each other, but nil is an object value while NULL is a generic pointer value ((void*)0, to be specific). [NSNull null] is an object that's meant to stand in for nil in situations where nil isn't allowed. For example, you can't have a nil value in an NSArray.

What is nil type in Swift?

In Swift, nil means the absence of a value. Sending a message to nil results in a fatal error. An optional encapsulates this concept. An optional either has a value or it doesn't. Optionals add safety to the language.


2 Answers

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"])
like image 51
Martin R Avatar answered Oct 23 '22 00:10

Martin R


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.

like image 21
Sulthan Avatar answered Oct 22 '22 23:10

Sulthan