加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何将不同类型的字典中的Swift语言?

发布时间:2020-12-14 06:08:52 所属栏目:百科 来源:网络整理
导读:Swift只允许字典包含单个类型。 这里的定义是从Swift的书: A dictionary is a container that stores multiple values of the same type […] They differ from Objective-C’s NSDictionary and NSMutableDictionary classes,which can use any kind of ob
Swift只允许字典包含单个类型。

这里的定义是从Swift的书:

A dictionary is a container that stores multiple values of the same type

[…]

They differ from Objective-C’s NSDictionary and NSMutableDictionary classes,which can use any kind of object as their keys and values and do not provide any information about the nature of these objects.

如果是这样,那么我们将如何创建嵌套的字典?

想象一下,我们有一个plist,它包含String,Array和Dictionary项。如果我允许只保持相同的类型的项目(字符串,数组等),那么我将如何使用存储在plist中的不同类型的项目?

如何把不同类型放在同一个字典在Swift?

你可以使用任何类型的字典值来实现plist类嵌套结构,它是Swift的一些对应于Objective-C的id类型,但也可以保存值类型。
var response = Dictionary<String,Any>()
response["user"] = ["Login": "Power Ranger","Password": "Mighty Morfin'"]
response["status"] = 200

编辑:

任何似乎比AnyObject更好,因为在上面的代码response [“status”]是类型Swift.Int,而使用值类型AnyObject它是__NSCFNumber。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读