ios - nil 合并运算符 '??' 的左侧具有非可选类型 'String' ,因此从不使用右侧

标签 ios swift option-type forced-unwrapping

我有下面的代码,我试图用它来初始化一个变量并对它执行一些操作。

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 to model.pointsCategory if model.pointsCategory is not nil. If it is nil, set self.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/

相关文章:

ios - 如何等待几秒钟以确保在执行之前没有任何反应

ios - 旋转设备时如何更改 SKScene 大小?

javascript - 聆听点击和拖动的值并相应地运行

ios - 怎么打重法?

ios - XCode 8 缺少代码签名身份调试

ios - 快速点击删除后单元格滞后

spring-boot - 如何设置 spring boot 中可选的 getter 和 setter 方法的值

ios - 展开可选时崩溃

java - Optional Of Nullable 当 map 返回 null 时执行 orElse

objective-c - iOS:如何将 "cartoon"风格的动画(电影)添加到幻灯片中?