Swift:模型结构,使用选项与空值的初始化 [英] Swift: model structs, using optionals vs initialization of empty values

查看:219
本文介绍了Swift:模型结构,使用选项与空值的初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Swift 中,例如我对这个模型我有 struct

In Swift, say for example I have a struct for this model:

struct Message {
    var message: String = ""
    var timestamp: String = ""
    var id: String = ""
}

我将从数据库中使用此 struct 实例化多个消息,然后填充 TableView 与它们一起使用。

And I would be instantiating multiple Messages using this struct from a database, and then populate a TableView with them.

使用选项而不是用空字符串设置这些变量是最佳做法吗?

Would it be best practice to using optionals instead of setting these variables with empty strings like such?

struct Message {
    var message: String?
    var timestamp: String?
    var id: String?
}

基本上将变量设置为<$更高效吗? c $ c> nil vs 空字符串 nil 占用更少内存vs 空字符串

Would it be more efficient to basically setting the variables to nil vs an empty string? Does nil take less memory vs empty string?

推荐答案

在考虑优化之前,你必须问自己一个好问题:消息是否有可能包含选项一个或几个属性?如果是,请使用选项,如果不是,请不要使用选项。

Before thinking about optimization, you have to ask yourself the good question: is there any chance that Message may contain optionals for one or several of its properties? If yes, use optionals, if no, don't use optionals.

然后,如果要改进代码,可以使用 memberwise initializer 用于 struct

Then, if you want to improve your code, you can use memberwise initializer for your struct:

struct Message {
    var message: String
    var timestamp: String?
    var id: String
}

let message = Message(message: "Some message", timestamp: nil, id: "Id14")

最后,我怀疑 Struct 上的任何内存优化(带可选或非可选)属性)将对您的应用程序/项目进行任何重大改进。

Finally, I doubt any memory optimization on Struct (with optional or non optional properties) will give any significant improvement to your app/project.

这篇关于Swift:模型结构,使用选项与空值的初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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