When should you use options and when should you use non-optional values ​​with default values?

I know it's recommended to use in Swift:

class Address {
var firstLine : String?
var secondLine : String?
}

      

but sometimes I see other developers write their code like this:

class Address {
var firstLine : String = ""
var secondLine : String = ""
}

      

This is an unmanageable way, because whenever you have nil

, you will just crash and there is no way out to recover. It is right? Or there are some use cases where using non-default options might be good. If so, where?

I saw this other question that asks about efficiency rather than which one best suits your needs. I'm looking for an answer that says, "This is a good place to use non-optional, and this is a good place to use options." Sometimes I see people just dumping options all over the place and that makes me think that we never need non-options? Sometimes I see people trying to avoid options as much as possible and just Objective-C style code.

The above answer to the question does not represent a valid case where non-optional are good. It's dumb about it. As for the choice of options: I am assuming that for models that are populated with network calls, options are the right choice because you don't know if it is nil

or not.

+4


source to share


2 answers


The choice depends on what you are modeling.

If the property of the object you are modeling may be missing entirely, eg. middle name, name suffix, alternate phone number, etc., it must be modeled with the option. A nil

optional tells you that this property is not there, i.e. The person doesn't have a middle name or alternative phone number. You should also use the option when you must distinguish between an empty object and a missing object.

If an object property is to be set and has a default value, use an optional parameter with a default value:



class AddressList {
    var addresses : [Address]
    var separator : String = ";"
    ...
}

      

If the users of your class need to change the separator, they have a way to do it. However, if they don't care about the delimiter, they can continue to use the default without mentioning it in their own code.

+6


source


Well, you should use options if you think the variable might not matter. But if you are really confident that it will have value, you will not need to use them.



Therefore, only use optional options if you are sure that the variable will have the value else using options.

0


source







All Articles