Swift: model structs using options and null initialization

In Swift

, for example, I have struct

for this model


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


And I would create several Messages

using this one struct

from the database and then populate them TableView


Would it be better to use alternatives instead of setting these variables with empty strings like this?

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


Would it be more efficient to set variables in nil

vs a empty string

? The smaller nil

less memory vs empty string



source to share

2 answers

Before thinking about optimization, you should ask yourself a good question: is there a chance that there Message

might be options for one or more of its properties? If yes, use options, if not, do not use additional options.

Then, if you want to improve your code, you can use a member 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 that optimizing memory on struct

(with additional or optional properties) will result in a significant improvement in your application / project.



Avoid options whenever possible. Stored properties are not as magical as in objective-c. Just give them their defaults if appropriate.



All Articles