簡體   English   中英

nil 合並運算符 '??' 的左側具有非可選類型“字符串”,因此從不使用右側

[英]Left side of nil coalescing operator '??' has non-optional type 'String', so the right side is never used

我有以下代碼,我試圖用它來初始化一個變量並對其執行一些操作。

let formattedPointsValue: String?
self.formattedPointsValue = model.pointUnitsEarned.stringValueWithWhiteSpaceThousandSeperator()+" "+"model.name".localized(in: .name) ?? .none

但是我收到警告

nil 合並運算符 '??' 的左側具有非可選類型“字符串”,因此從不使用右側。

當我刪除?? .none ?? .none我的項目運行良好沒有問題但是當我運行我的單元測試時出現錯誤

致命錯誤:在解開 Optional 值時意外發現 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

我想你對??有點困惑。 運營商。

你認為這是可行的,因為legend是可選的,不是嗎?

let legend: String?
self.legend = model.pointsCategory ?? .none

這不是原因! 上述工作的實際原因是因為model.pointsCategory是可選的。 它與=左側的內容無關。 都是關於??左邊的操作數 . 所以上面說的是這樣的:

self.legendmodel.pointsCategory如果model.pointsCategory不為零。 如果為 nil,請將self.legend設置為.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)
}

.name 屬性不是可選的,這就是為什么會出現錯誤使 .name 屬性在模型中可選

?? 只有當左邊的值可以是nil時才有用,

Swift 告訴你它永遠不會是nil所以右邊的值永遠不會被使用。 您可以刪除: String? 以及。

model.pointsCategory的值是可選的,所以可能是nil ,這就是為什么它適用model.pointsCategory並且不會給您任何錯誤或警告。

nil 合並運算符的要點是,如果值不存在,則能夠回退到默認值,如果始終存在值,則使用它沒有意義,所以這就是您收到警告的原因。

model.pointUnitsEarned.stringValueWithWhiteSpaceThousandSeperator()+" "+"model.name".localized(in: .name)==> 應該返回可選字符串的值

例如:下面的代碼將得到與您收到的相同的錯誤

let nickName: String = "k"
let fullName: String? = "John Appleseed"
let informalGreeting = "Hi \(nickName ?? fullName)"

但是下面的代碼可以正常工作。

let nickName: String? = nil
let fullName: String = "John Appleseed"
let informalGreeting = "Hi \(nickName ?? fullName)"

所以結論是Coalescing operator '??' 將替換或使用從右側到左側的默認值。 不是從左到右。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM