如何在Swift中将NSNull转换为nil?

Bla*_*ard 14 swift xcode6

我想从我的服务器获取JSON数据并在启动时对其进行操作.在Objective-C中,我使用此#define代码转换NSNullnil,因为获取的数据有时可能包含null.

#define NULL_TO_NIL(obj) ({ __typeof__ (obj) __obj = (obj); __obj == [NSNull null] ? nil : obj; })
Run Code Online (Sandbox Code Playgroud)

但是,在Swift中,是否有可能将其转换NSNullnil?我想使用以下操作(代码是Objective-C):

people.age = NULL_TO_NIL(peopleDict["age"]);
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,当获取数据的age键是NULL,则将people对象的.age属性设置为nil.

我使用Xcode 6 Beta 6.

Mar*_*n R 37

这可能是你正在寻找的:

func nullToNil(value : Any?) -> Any? {
    if value is NSNull {
        return nil
    } else {
        return value
    }
}

people.age = nullToNil(peopleDict["age"])
Run Code Online (Sandbox Code Playgroud)


Sul*_*han 9

我建议,而不是使用自定义转换函数,只是使用as?以下方式来转换值:

people.age = peopleDict["age"] as? Int
Run Code Online (Sandbox Code Playgroud)

如果值为NSNull,则转换as?将失败并返回nil.