在 Swift 中使用 Int 类型与 IndexPath 类型

Using an Int type versus IndexPath type in Swift

我正在阅读一本教程书,但我对我们如何访问 Swift 中的数组有疑问。我很想知道如果我直接使用 IndexPath 类型会发生什么,因为我假设此类型代表树或数组中特定节点的路径。但是,以下函数在 returns 行显示错误:"Cannot subscript value of type [ToDoItem] with an index of type IndexPath"

func item(at indexIWant: IndexPath) -> ToDoItem {

        return toDoItems[indexIWant]
    }

我只是想知道这在外行人看来是什么意思,为什么不能接受?

这里是教程中的代码,使用 IndexPath 类型而不是 IndexPath 类型进行编译。

import Foundation


class ItemManager {

    var toDoCount: Int = 0

    var doneCount: Int = 0

    private var toDoItems: [ToDoItem] = []

    func add(_ item: ToDoItem) {

        toDoCount += 1

        toDoItems.append(item)
    }


    func item(at index: Int) -> ToDoItem {

        return toDoItems[index]

    }
}

The NSIndexPath class represents the path to a specific node in a tree of nested array collections

所以row是数组n的索引,section是数组的序号 所以第一个箭头来自 row 1 和 section 0,第二个箭头来自 row 4 和 section 1..等等。

Doc

因为 subscript 需要 Int 而您传递的 IndexPath 不是 Int.

类型

如果您查看 Apple IndexPath DocumentationIndexPath 具有类型为 Introwsection 等属性。您可以使用它们访问数组中的元素。

func item(at indexIWant: IndexPath) -> ToDoItem {
    return toDoItems[indexIWant.row]
}

如果您真的想使用 IndexPath 访问数组,您可以扩展数组 class。现在你的代码可以编译了,但我不确定我是否推荐这个代码。

extension Array {
    subscript(indexPath: IndexPath) -> Element {
        get {
            return self[indexPath.row]
        }
        set {
            self[indexPath.row] = newValue
        }
    }
}