Swift可选链理解误区:为何代码输出无法获取候选名?
Swift可选链代码输出原理说明
你对可选链的理解偏差在于:默认认为类的可选类型属性会自动初始化对应实例,忽略了可选类型未赋值时默认值为nil的规则,以及可选链遇nil直接返回的核心逻辑。
逐段逻辑拆解
- 首先看属性默认值规则:
你定义的ElectionPoll类中,candidate是Pollbooth?可选类型属性,代码中没有为它设置初始值。Swift语法规定,没有手动赋初始值的可选类型属性,默认值为nil。
执行let cand = ElectionPoll()时,仅完成了ElectionPoll实例本身的初始化,它的candidate属性没有被赋值,此时cand.candidate就是nil,没有指向任何Pollbooth类的实例。 - 再看可选链的执行逻辑:
可选链的?操作符执行规则非常明确:访问链式属性时,会先判断?前面的可选值是否为nil:- 如果值非
nil,则解包该值,继续向后访问后续属性,最终将访问结果包装为可选类型返回; - 如果值为
nil,则直接终止整条调用链,立刻返回nil,不会执行后续的属性访问逻辑。
你的代码里cand.candidate为nil,因此cand.candidate?.name会直接返回nil,if let可选绑定失败,自然会进入else分支,输出Candidate name cannot be retreived。
- 如果值非
实现预期输出的修改方式
只需要在访问可选链前,手动为candidate属性赋值一个Pollbooth实例即可:
class ElectionPoll { var candidate: Pollbooth? } class Pollbooth { var name = "MP" } let cand = ElectionPoll() cand.candidate = Pollbooth() // 为可选属性赋值实例,此时candidate不再是nil if let candname = cand.candidate?.name { print("Candidate name is \(candname)") // 进入该分支,输出预期内容 } else { print("Candidate name cannot be retreived") }
内容的提问来源于stack exchange,提问作者Vyankatesh
相关产品推荐
相关产品推荐

