I'm working through a tutorial book and I have a question about how we access arrays in Swift. I was curious to know what would happen if I use an IndexPath type directly since I assume this type represents a path to a specific node within a tree or array. However, the following function shows an error on the line that returns which says: "Cannot subscript value of type [ToDoItem] with an index of type IndexPath"
func item(at indexIWant: IndexPath) -> ToDoItem {
return toDoItems[indexIWant]
}
I'm just curious to know what does this mean in layman terms and why isn't this acceptable?
Here is the code from the tutorial and that compiles which uses an Int type instead of type 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]
}
}
Because the subscript
expects an Int
and you're passing an IndexPath
which is not of type Int
.
If you have a look at the Apple IndexPath Documentation, IndexPath
has properties like row
or section
that are of type Int
. You can use them to access an element from your array.
func item(at indexIWant: IndexPath) -> ToDoItem {
return toDoItems[indexIWant.row]
}
If you really want to access an array with IndexPath
, you could extend the Array class. Now your code compiles but I am not sure if I recommend this code.
extension Array {
subscript(indexPath: IndexPath) -> Element {
get {
return self[indexPath.row]
}
set {
self[indexPath.row] = newValue
}
}
}