Take the two snippets below, the top one works fine but the bottom one results in Ambiguous use of 'subscript(_:)'
using index ✅
extension Array {
subscript(i index: Int) -> (String, String)? {
guard let value = self[index] as? Int else {
return nil
}
switch (value >= 0, abs(value % 2)) {
case (true, 0): return ("positive", "even")
case(true, 1): return ("positive", "odd")
case(false, 0): return ("negative", "even")
case(false, 1): return ("negative", "odd")
default: return nil
}
}
}
Without using index ❌
extension Array {
subscript(i: Int) -> (String, String)? {
guard let value = self[i] as? Int else {
return nil
}
switch (value >= 0, abs(value % 2)) {
case (true, 0): return ("positive", "even")
case(true, 1): return ("positive", "odd")
case(false, 0): return ("negative", "even")
case(false, 1): return ("negative", "odd")
default: return nil
}
}
}
CodePudding user response:
First, the name index
is irrelevant to the problem; it could be any name.
The actual problem is that Array
already has a subscript that takes an unlabeled Int
.
Your first overload does not have the same input signature. Instead, it requires an argument label:
[1][i: 0] // ("positive", "odd")
You can still use an overload without a label…
extension Array where Element: BinaryInteger {
subscript(