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.
A singleton object used to represent null values in collection objects that don't allow nil values.
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.
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.
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"])
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With