In Swift
, say for example I have a struct
for this model
:
struct Message {
var message: String = ""
var timestamp: String = ""
var id: String = ""
}
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?
}
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.
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")
Finally, I doubt any memory optimization on Struct
(with optional or non optional properties) will give any significant improvement to your app/project.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With