为什么可选常量不会自动具有默认值nil

编程入门 行业动态 更新时间:2024-10-11 23:17:38
本文介绍了为什么可选常量不会自动具有默认值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

本文发布于:2023-07-15 13:11:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1111411.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:常量   可选   默认值   nil

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!