SwiftUI:绑定数组的安全下标

use*_*265 5 swift swiftui combine

我们习惯于在访问集合中的任何元素时使用安全下标。下面是我们的扩展。

extension Collection {
    subscript(safe index: Index) -> Element? {
        return indices.contains(index) ? self[index] : nil
    }
}
Run Code Online (Sandbox Code Playgroud)

但是当我尝试将它与绑定对象一起使用时,它给了我一个错误说

下标中的无关参数标签“安全:”

下面是有问题的代码

struct MyView: View {
    @ObservedObject var service: service

    var body: some View {
        List {
            ForEach(service.items.indices) { index in
                Toggle(isOn: self.$service.items[safe: index]?.isOn ?? false) {  // Error: Extraneous argument label 'safe:' in subscript
                    Text("isOn")
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Joh*_* M. 5

两个问题:

  1. 您不需要使用items[safe: index],因为您只获得了有效索引items.indices。你永远不会有一个超出数组边界的索引。

  2. 你不能使用items[safe: index],因为 self.$service.items 是一个Binding<[Item]>,它不是一个集合,所以你对集合的扩展不适用。

只需删除safe:,你就可以开始了。

有关更多详细信息,请参阅此答案的结尾。