如何在 Swift 中将 NSNull 转换为 nil? [英] How to convert NSNull to nil in Swift?
问题描述
我想从我的服务器获取 JSON 数据并在启动时对其进行操作.在 Objective-C 中,我使用这个 #define
代码将 NSNull
转换为 nil
,因为有时获取的数据可能包含 null.
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; })
但是,在 Swift 中,是否可以将 NSNull
转换为 nil
?我想使用以下操作(代码是Objective-C的):
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"]);
上述代码中,当获取数据的age
键为NULL
时,则people
对象的.age
> 属性设置为 nil
.
In the above code, when the fetched data's age
key is NULL
, then the people
object's .age
property is set to nil
.
我使用 Xcode 6 Beta 6.
I use Xcode 6 Beta 6.
推荐答案
这可能就是您要找的:
func nullToNil(value : Any?) -> Any? {
if value is NSNull {
return nil
} else {
return value
}
}
people.age = nullToNil(peopleDict["age"])
这篇关于如何在 Swift 中将 NSNull 转换为 nil?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!