我有下面的代码,我试图用它来初始化一个变量并对它执行一些操作。
let formattedPointsValue: String?
self.formattedPointsValue = model.pointUnitsEarned.stringValueWithWhiteSpaceThousandSeperator()+" "+"model.name".localized(in: .name) ?? .none
但是我收到了警告
Left side of nil coalescing operator '??' has non-optional type 'String', so the right side is never used.
当我删除 时?? .none
我的项目运行良好,没有问题,但是当我运行单元测试时出现错误
fatal error: unexpectedly found nil while unwrapping an Optional value
我发现解决此问题的唯一方法是使用此代码。
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
最佳答案
我认为您对 ??
运算符有点困惑。
你认为这行得通是因为 legend
是可选的,不是吗?
let legend: String?
self.legend = model.pointsCategory ?? .none
这不是原因! 上面的工作的实际原因是因为 model.pointsCategory
是可选的。它与 =
左侧的内容无关。都是关于??
左边的操作数。所以上面说的是这样的:
set
self.legend
tomodel.pointsCategory
ifmodel.pointsCategory
is not nil. If it is nil, setself.legend
to.none
.
在这种情况下:
self.formattedPointsValue = model.pointUnitsEarned.stringValueWithWhiteSpaceThousandSeperator()+
" "+"model.name".localized(in: .name) ?? .none
由于 "model.name".localized(in: .name)
不是可选的,因此无法编译。我怀疑您打算在这里执行的操作可能是这样的:
if self.formattedPointsValue == nil {
self.formattedPointsValue = .none
} else {
self.formattedPointsValue = model.pointUnitsEarned.stringValueWithWhiteSpaceThousandSeperator()+
" "+"model.name".localized(in: .name)
}
关于ios - nil 合并运算符 '??' 的左侧具有非可选类型 'String' ,因此从不使用右侧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49994795/