为什么可选常量不会自动具有默认值nil [英] Why optional constant does not automatically have a default value of nil

查看:85
本文介绍了为什么可选常量不会自动具有默认值nil的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码可以正常工作

struct carConfi {
    var owner: String?
    let brand: String = "BMW"
    var currentMile: Double = 2000
}

let tomCar = carConfi()

但是,如果我将属性owner的类型更改为常量,则初始化器会出现错误

However, if I change the type of the property owner to constant, there will be an error at the initializer

struct carConfi {
        let owner: String? // Change to constant
        let brand: String = "BMW"
        var currentMile: Double = 2000
    }

let tomCar = carConfi() //error: missing argument for parameter 'owner' in call 

我做了一些搜索,结果发现这是因为 optional 变量自动具有默认值nil

I did a bit search, it turns out that it is because the optional variables automatically have a default value of nil

我猜:因为一旦设置了常量,就无法更改它,如果可选常量自动收到一个nil,则它将保持为不可更改的nil,这非常愚蠢,可能会违反用户的要求

I guess: Because once the constant is set, it then cannot be changed, if the optional constant automatically received an nil then it will keep as an unchangeable nil that's very silly and may against the users will

问题:我的大学并不完全相信这一猜测,他告诉我,必须有更多的理由.如果有人可以向我解释,我将不胜感激

Question: My college doesn't fully convinced by the guess, he told me there must be more reasons for that. I would very appreciate if someone can explain that to me

Thx

推荐答案

不使用以下任一方法设置只读(常量)字段:

Not setting a read-only (constant) field with either an:

  • 初始化表达式
  • 初始化器

几乎可以肯定是程序错误的指示.

is almost certainly an indication of an error in your program.

由于没有其他机会设置let字段的值,因此该字段的值将保持为nil(或其他一些默认值).程序员不太可能会发现这种行为是可取的,并故意提出要求.

Since you have no other opportunity to set the value of your let field, the value of the field is going to remain nil (or some other default). It is rather unlikely that a programmer would find such behavior desirable, and request it on purpose.

这就是为什么Swift将这种情况标记为错误.另一方面,如果您实际上希望String常量保持nil,则可以添加一个表达式以将其设置为nil,然后使错误静音:

That is why Swift marks this situation as an error. On the other hand, if you actually wanted your String constant to remain nil, you could add an expression to set it to nil, and silence the error:

let owner: String? = nil // Pretty useless, but allowed

这篇关于为什么可选常量不会自动具有默认值nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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