簡體   English   中英

三元快速展開

[英]Ternary Unwrapping in swift

我正在迅速使用以下代碼:

var categories: Results<Category>? //Realm dataType

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    if let categories = categories, !categories.isEmpty {
        return categories.count
    } else {
        return 1
    }
}

我現在正在尋找將tableView的代碼構造為三元運算符,但不知道該怎么做。 我找到了以下頁面: https : //dev.to/danielinoa_/ternary-unwrapping-in-swift-903,但我仍然不清楚。

我試過的是:

return categories?.isEmpty ?? {($0).count} | 1

要么

let result = categories?.isEmpty ?? {($0).count} | 1
return result

但都給錯誤。 知道我該如何解決嗎?

可以使用Optional.map代替三元,使其更加簡單:

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return categories.map { $0.count } ?? 1
}

或將Optional.map和三元混合使用以實現您認為要實現的目標:

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return categories.map { !$0.isEmpty ? $0.count : 1 } ?? 1
}
return categories?.count != 0 ? {($0).count} : 1

對於nil和空數組,返回1,否則返回count的值

return (categories?.count ?? 1) + (categories?.isEmpty ?? false ? 1 : 0)

暫無
暫無

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

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