Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: model structs, using optionals vs initialization of empty values

Tags:

var

null

ios

swift

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?

like image 562
The Nomad Avatar asked Oct 31 '22 16:10

The Nomad


1 Answers

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.

like image 56
Imanou Petit Avatar answered Nov 15 '22 07:11

Imanou Petit