Swift nil coalescing operator with array



我正在尝试创建一个简单的待办事项列表。 在引入 Realm 或 coreData 之前,我想测试一下,看看一切是否顺利。

我知道我可能可以在一些if 条件下完成这项工作,但我希望能够使用nil 合并运算符(我只是喜欢它的简单性(,而且我不确定为什么它不起作用。

我在没有它的情况下让它工作,但真的很感兴趣它表现这样的原因是什么。

当我启动应用程序时,它只显示"未添加类别">,即使我将一些项目添加到数组并打印出来,列表也保持不变。

import UIKit
class CategoriesTableView: UITableViewController {
var testData = [FauxData]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.reloadData()
}
// MARK: - Data Methods
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let data = testData[indexPath.row].categoryTitle ?? "No Category Added"
cell.textLabel?.text = data
return cell
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return testData.count
}
@IBAction func addItem(_ sender: UIBarButtonItem) {
CreateNewItem(item: "test")
tableView.reloadData()
}
func CreateNewItem(item: String) {
let newItem = FauxData()
newItem.categoryTitle = item
testData.append(newItem)
print(item)
}
}

这是类 FauxData:

class FauxData {
var categoryTitle: String?
}

如果这太简单或重复,我无法找到合适的答案。

不幸的是,索引空数组会崩溃而不是返回nil,因此您不能使用nil 合并运算符。 相反,请将.isEmpty属性与?:运算符一起使用以实现目标:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let data = testData.isEmpty ? "No Category Added" : testData[indexPath.row].categoryTitle
cell.textLabel?.text = data
return cell
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return testData.isEmpty ? 1 : testData.count
}

注意:当数组为空时,您必须从tableView(_:numberOfRowsInSection:)返回1,以便调用tableView(_:cellForRowAt:)以返回默认消息。


如果实现安全数组索引,则可以使用nil 合并运算符

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let data = testData[safe: indexPath.row]?.categoryTitle ?? "No Category Added"
cell.textLabel?.text = data
return cell
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return testData.isEmpty ? 1 : testData.count
}

最新更新