5

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?

The Nomad
  • 7,155
  • 14
  • 65
  • 100
  • highly recommend to see [this](https://stackoverflow.com/questions/44288488/when-should-i-use-optionals-and-when-should-i-use-non-optionals-with-default-val) question. The answer there gives a good explanation. – mfaani May 31 '17 at 16:09

2 Answers2

8

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.

Imanou Petit
  • 89,880
  • 29
  • 256
  • 218
  • Good question to ask myself. In my case, I would say no chance for `nil` since they will be coming from a database. And I would rather leave empty/default values instead of `null` in my db. Thanks for the help! – The Nomad Sep 25 '14 at 03:49
-6

Avoid optionals whenever it is possible. Stored properties are not as magical as they are in objective-c. Just give them default values if it is appropriate.

mustafa
  • 15,254
  • 10
  • 48
  • 57