Bjo*_*aye 0 ternary-operator optional ios swift unwrap
在 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
}
}
Run Code Online (Sandbox Code Playgroud)
我现在希望将 tableView 的代码构建为三元运算符,但不知道如何执行此操作。我找到了以下页面:https : //dev.to/danielinoa_/ternary-unwrapping-in-swift-903但我仍然不清楚。
我试过的是:
return categories?.isEmpty ?? {($0).count} | 1
Run Code Online (Sandbox Code Playgroud)
或者
let result = categories?.isEmpty ?? {($0).count} | 1
return result
Run Code Online (Sandbox Code Playgroud)
但两者都给出错误。知道我该如何解决这个问题吗?
你可以用Optional.map它来简化它,而不是三元:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return categories.map { $0.count } ?? 1
}
Run Code Online (Sandbox Code Playgroud)
或者混合Optional.map和三元来实现我认为要实现的目标:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return categories.map { !$0.isEmpty ? $0.count : 1 } ?? 1
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
582 次 |
| 最近记录: |