Ambiguous Subscript

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
            
        }
    }
}

How come the code above works but the code below doesnโ€™t work and keeps saying ambiguous subscript?

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
            
        }
    }
}

@shogunkaramazov any suggestions?

Hi @jinkazama ,
it is an interesting one, I could be wrong but it has something to do with the compiler and the parameter names.

If I change the second function block as subscript(i i : Int) -> it works, so what I can say at a surface level is that it needs an internal variable in this scenario.

The generated interface for this looks like
internal subscript(i i: Int) -> (String, String)? { get }
where as the compiler fails to generate the interface for the second block without an internal parameter.

i think it has something to do with the Swift Compiler and/or a clash with the default array subscript signature.

3 Likes

This topic was automatically closed after 166 days. New replies are no longer allowed.