When should I use optionals and when should I use non-optionals with default values?

后端 未结 2 1469
南方客
南方客 2021-01-03 02:14

I know the recommended way in Swift is to use:

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

but sometimes I see other

2条回答
  •  没有蜡笔的小新
    2021-01-03 02:50

    The choice depends on what you model.

    If a property of the object that you model may be absent completely, e.g. a middle name, a name suffix, an alternative phone number, etc., it should be modeled with an optional. A nil optional tells you that the property is not there - i.e. a person does not have a middle name or an alternative phone number. You should also use optional when you must distinguish between an empty object and a missing object.

    If a property of the object must be set, and has a meaningful default, use an non-optional with a default:

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

    If users of your class need to change the separator, they have a way to do that. However, if they do not care about the separator, they can continue using the default without mentioning it in their own code.

提交回复
热议问题