Swift:如何无冗余代码解包永不为nil的已初始化可选变量
问题描述
给定示例类(实际业务场景更复杂,因此不修改变量初始化方式及该属性的可选类型设定),当前编写的getInformation()函数在XCode中触发报错:Value of optional type 'String?' must be unwrapped to a value of type 'String'。需在不编写冗余代码(如合并运算符、无效返回值、抛出异常等)的前提下,返回永不为nil的String类型值,寻求可行的解包方案。
示例代码
public class Thing { var information: String? = nil func getInformation() -> String { if let information { return information } else { information = functionThatReturnsNonOptionalString() return information // 此处报错 } } }
需避免的冗余代码示例
- 合并运算符:
return information ?? ""
- 无效返回值:
if let information { } else { return "" }
- 抛出异常:
if let information { } else { throw Error() }
可行解包方案
方案1:安全强制解包
由于functionThatReturnsNonOptionalString()返回的是非可选String,赋值给information后该属性必然不为nil,因此可安全使用强制解包:
public class Thing { var information: String? = nil func getInformation() -> String { if let information { return information } else { information = functionThatReturnsNonOptionalString() return information! } } }
方案2:直接返回赋值结果
利用赋值操作的返回值特性,直接返回functionThatReturnsNonOptionalString()的结果(同时完成属性赋值),无需解包:
public class Thing { var information: String? = nil func getInformation() -> String { if let information { return information } else { return information = functionThatReturnsNonOptionalString() } } }
方案3:临时变量绑定
通过临时变量存储非可选结果,同时完成属性赋值并返回:
public class Thing { var information: String? = nil func getInformation() -> String { if let information { return information } else { let nonOptionalInfo = functionThatReturnsNonOptionalString() information = nonOptionalInfo return nonOptionalInfo } } }
内容的提问来源于stack exchange,提问作者Regular User
相关产品推荐
相关产品推荐

