We have the practice of using safe subscript when accessing any element in a collection. Below is the extension we have.
extension Collection {
subscript(safe index: Index) -> Element? {
return indices.contains(index) ? self[index] : nil
}
}
But when I try to use this with a binding object, it gives me an error saying
Extraneous argument label 'safe:' in subscript
Below is the problematic code
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")
}
}
}
}
}
Two issues:
You don't need to use items[safe: index]
, because you are given only valid indices by items.indices
. You will never have an index that is outsides the bounds of the array.
You can't use items[safe: index]
, because self.$service.items is a Binding<[Item]>
, which is not a Collection, so your extension to Collection doesn't apply.
Just remove the safe:
and you're good to go.
See the end of this answer for more detail.
The diagnostic message is confusing, but the problem is that your subscript returns an optional, but you're treating it like a non-optional. You're going to have to handle the case where it returns nil.
Personally I think this approach is fighting the system. You'd be better off using ForEach(service.items)
. Rather than "safe" subscripts, avoid subscripts entirely.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With