【发布时间】:2018-10-04 07:24:22
【问题描述】:
我有以下代码,我试图用它来初始化一个变量并对其执行一些操作。
let formattedPointsValue: String?
self.formattedPointsValue = model.pointUnitsEarned.stringValueWithWhiteSpaceThousandSeperator()+" "+"model.name".localized(in: .name) ?? .none
但是我收到了警告
nil 合并运算符 '??' 的左侧具有非可选类型“字符串”,因此从不使用右侧。
当我删除 ?? .none 时,我的项目运行良好,没有问题,但是当我运行单元测试时出现错误
致命错误:在展开可选值时意外发现 nil
我发现解决此问题的唯一方法是使用此代码。
if let unformattedValue = model.pointUnitsEarned {
self.formattedPointsValue = unformattedValue.stringValueWithWhiteSpaceThousandSeperator()+" "+"model.name".localized(in: .name)
} else {
self.formattedPointsValue = nil
}
我想了解为什么这样的事情有效:
let legend: String?
self.legend = model.pointsCategory ?? .none
但这失败了:
let formattedPointsValue: String?
self.formattedPointsValue = model.pointUnitsEarned.stringValueWithWhiteSpaceThousandSeperator()+" "+"model.name".localized(in: .name) ?? .none
【问题讨论】:
标签: ios swift optional forced-unwrapping