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

Ere*_*ent 5 ios swift forced-unwrapping option-type

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

let formattedPointsValue: String?
self.formattedPointsValue = model.pointUnitsEarned.stringValueWithWhiteSpaceThousandSeperator()+" "+"model.name".localized(in: .name) ?? .none
Run Code Online (Sandbox Code Playgroud)

但是我收到警告

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

当我删除?? .none我的项目时,我的项目运行良好,没有问题,但是当我运行单元测试时,我收到错误

致命错误:在解包可选值时意外发现 nil

我发现解决这个问题的唯一方法是使用这段代码。

if let unformattedValue = model.pointUnitsEarned {
    self.formattedPointsValue = unformattedValue.stringValueWithWhiteSpaceThousandSeperator()+" "+"model.name".localized(in: .name)
} else {
    self.formattedPointsValue = nil
}
Run Code Online (Sandbox Code Playgroud)

我想了解为什么这样的事情有效:

let legend: String?
self.legend = model.pointsCategory ?? .none
Run Code Online (Sandbox Code Playgroud)

但这失败了:

let formattedPointsValue: String?
self.formattedPointsValue = model.pointUnitsEarned.stringValueWithWhiteSpaceThousandSeperator()+" "+"model.name".localized(in: .name) ?? .none
Run Code Online (Sandbox Code Playgroud)

Swe*_*per 5

我认为您对运营商有点困惑??

您认为这有效是因为它legend是可选的,不是吗?

let legend: String?
self.legend = model.pointsCategory ?? .none
Run Code Online (Sandbox Code Playgroud)

不是这个原因!上述工作的实际原因是因为model.pointsCategory是可选的。它与 的左侧内容无关=。这都是关于 左边的操作数??。所以上面说的是这样的:

如果不为零则设置self.legend为。如果为零,则设置为。model.pointsCategorymodel.pointsCategoryself.legend.none

在这种情况下:

self.formattedPointsValue = model.pointUnitsEarned.stringValueWithWhiteSpaceThousandSeperator()+
    " "+"model.name".localized(in: .name) ?? .none
Run Code Online (Sandbox Code Playgroud)

由于"model.name".localized(in: .name)不是可选的,因此无法编译。我怀疑你在这里打算做的可能是这样的:

if self.formattedPointsValue == nil {
    self.formattedPointsValue = .none
} else {
   self.formattedPointsValue = model.pointUnitsEarned.stringValueWithWhiteSpaceThousandSeperator()+
        " "+"model.name".localized(in: .name)
}
Run Code Online (Sandbox Code Playgroud)