Swift-结构或字典 [英] Swift - Struct or Dictionary

查看:56
本文介绍了Swift-结构或字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,当存储字典样式的结构化数据时,例如:

In general, when storing dictionary style structured data such as:

let menuItems = [
    [
        "title": "View Profile",
        "icon": "iconSideProfile"
    ],
    [
        "title": "Invite Friends",
        "icon": "iconSideHeart"
    ],
    [
        "title": "Settings",
        "icon": "iconSideSettings"
    ],
    [
        "title": "Help",
        "icon": "iconSideHelp"
    ],
    [
        "title": "Logout",
        "icon": "iconSideLogout"
    ]
]

如果我们有一系列包含标题和图标的词典,那么将词典存储为词典或结构是更好的做法吗?

where we have an array of dictionaries that contain a title and an icon, is it better practice to store the dictionaries as dictionaries or structs?

struct MenuItem {
    let title: String
    let icon: String
}

let menuItems = [
    MenuItem(title: "View Profile", icon: "iconSideProfile"),
    ...
]

存储在结构中的优点是可以更好地定义数据,这意味着您不必在某些情况下明确表示字典将包含此键.

The advantages of storing in a struct being that the data is better defined, meaning you don't have to explicitly say that the dictionary will contain this key in some cases etc.

还是这太浪费资源了?

推荐答案

当您担心使用 struct 占用内存资源时,只需要澄清一点.结构是值复制的传递类型.与类(引用类型)不同,它没有存储在内存堆中.

Just to clarify one point when you are worried about memory resources by using struct. A structure is value copied passed type. It's not stored in the memory heap unlike classes (Reference types).

因此,请使用苹果自己推荐的 struct .

So go and use struct, it's recommended by Apple itself.

这篇关于Swift-结构或字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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