1

我正在尝试创建一个简单的待办事项列表。在介绍 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?
}

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

4

1 回答 1

1

不幸的是,索引一个空数组会崩溃而不是返回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
}

注意:您必须1tableView(_:numberOfRowsInSection:)数组为空时返回,以便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
}
于 2018-05-15T01:39:30.907 回答