什么时候应该使用可选选项,什么时候应该使用具有默认值的非可选选项? [英] When should I use optionals and when should I use non-optionals with default values?

查看:86
本文介绍了什么时候应该使用可选选项,什么时候应该使用具有默认值的非可选选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道Swift中推荐的使用方式:

I know the recommended way in Swift is to use:

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

但是有时我看到其他开发人员以这种方式编写代码:

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

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

这是不建议的方法,因为只要您拥有nil,您都将崩溃,并且没有恢复的出路.是对的吗?或者在某些用例中,将非可选选项与默认值配合使用可能会很好.如果是这样,那么在哪里?

Is this the unrecommended way because whenever you have nil you will just crash and there's no outlet for your to recover. Is that right? Or there are some use cases where using non-optionals with default can be good. If so then where?

我看到了另外一个问题这是在问效率,而不是哪个更适合您的需求.我正在寻找一个答案,上面写着这是使用非可选选项的好地方,这是使用可选选项的好地方." 有时我看到人们只是到处乱扔可选内容,这使得我认为我们永远都不需要非可选吗?有时候,我看到人们试图尽可能避免使用可选参数,而只是以一种Objective-C的风格进行编码.

I saw this other question which is asking about efficiency rather than which better suits your needs. I'm looking for an answer where it says "This is a good place to use non-optionals and this is a good place to use optionals". Sometimes I see folks just dump optionals everywhere and it makes me think do we not ever need non-optionals? Sometimes I see people trying to avoid optionals as much as possible and just code in an Objective-C kind of style.

上面的问题的答案并不代表非可选项很好的有效案例.这很无语.至于选择可选项:我猜是在通过网络调用填充的模型中,可选项是正确的选择,因为您不知道它是否为nil.

The above question's answer doesn't represent a valid case for where non-optionals are good. It's mute about that. As for choosing optionals: I'm guessing for models which get populated by network calls, optionals are the right choice, because you don't know whether it's nil or not.

推荐答案

选择取决于您的模型.

如果您建模的对象的属性可能完全不存在,例如中间名,名称后缀,备用电话号码等,应使用可选的名称进行建模. nil可选项告诉您该属性不存在-即一个人没有中间名或备用电话号码.当您必须区分空对象和缺失对象时,也应该使用可选.

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.

这篇关于什么时候应该使用可选选项,什么时候应该使用具有默认值的非可选选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆