如何在 Swift 中将 NSNull 转换为 nil? [英] How to convert NSNull to nil in Swift?

查看:38
本文介绍了如何在 Swift 中将 NSNull 转换为 nil?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的服务器获取 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆