简体   繁体   English

Swift-结构或字典

[英]Swift - Struct or Dictionary

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

Or is this too wasteful of resources? 还是这太浪费资源了?

Just to clarify one point when you are worried about memory resources by using struct . 当您担心使用struct占用内存资源时,只想澄清一点。 A structure is value copied passed type. 结构是值复制的传递类型。 It's not stored in the memory heap unlike classes (Reference types). 它不像类(引用类型)那样存储在内存堆中。

So go and use struct , it's recommended by Apple itself. 因此,请使用struct ,这是Apple本身推荐的。

Yes, it is always better to use data structures (struct or class). 是的,使用数据结构(结构或类)总是更好。 Using a dictionary is error prone, uses more memory, uses more CPU time, and costs you tons of man-hours when you have to find and fix bugs that don't show up until the software is running and crashing. 使用字典容易出错,会占用更多的内存,会占用更多的CPU时间,并且当您不得不查找和修复直到软件运行并崩溃时才会显示的错误时,会花费大量的工时。 Typos in the names of variables get caught by the compiler but typos in strings used as keys to a dictionary just cause weird errors while the software is running and sometimes those show up long after you moved on and some poor soul is stuck maintaining this code. 变量名中的错别字会被编译器捕获,但是用作字典键的字符串中的错别字只会在软件运行时引起奇怪的错误,有时这些错字会在您继续使用很长时间后出现,并且有些可怜的人坚持维护此代码。

A dictionary is for when you have a lot of different and usually unpredictable strings for the keys. 字典适用于键有很多不同且通常不可预测的字符串的情况。 You have the same two strings over and over and they will never change. 一遍又一遍地有两个相同的字符串,它们永远不会改变。 There is no reason not to use a struct or a class and every reason to avoid using the dictionary like you show in your question. 没有理由不使用结构或类,并且没有理由避免使用问题中显示的字典。 To be blunt, that dictionary is plain bad code and should be avoided at all costs. 坦白地说,该词典是普通的错误代码,应不惜一切代价避免使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM