Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

140
Vistas
Overload dictionary subscript two times and forward call

I'm trying to extend Dictionary and allow extracting values casted to a certain types and with a given default value. For this I added two overloads for the subscript function, one with a default value, one without:

extension Dictionary {

    subscript<T>(_ key: Key, as type: T.Type, defaultValue: T?) -> T? {
        // the actual function is more complex than this :)
        return nil
    }

    subscript<T>(_ key: Key, as type: T.Type) -> T? {
        // the following line errors out:
        // Extraneous argument label 'defaultValue:' in subscript
        return self[key, as: type, defaultValue: nil]
    }
}

However when calling the three-argument subscript from the two-argument one I get the following error:

Extraneous argument label 'defaultValue:' in subscript

enter image description here

Is this a Swift limitation? Or am I missing something?

I'm using Xcode 10.2 beta 2.

P.S. I know there are other alternatives to this, like dedicated functions or nil coalescing, trying to understand what went wrong in this particular situation.

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Subscripts have different rules than functions when it comes to argument labels. With functions, argument labels default to the parameter name – for example if you define:

func foo(x: Int) {}

you would call it as foo(x: 0).

However for subscripts, parameters don't have argument labels by default. Therefore if you define:

subscript(x: Int) -> X { ... }

you would call it as foo[0] rather than foo[x: 0].

Therefore in your example with the subscript:

subscript<T>(_ key: Key, as type: T.Type, defaultValue: T?) -> T? {
    // the actual function is more complex than this :)
    return nil
}

The defaultValue: parameter has no argument label, meaning that the subscript would have to be called as self[key, as: type, nil]. In order to add the argument label, you need to specify it twice:

subscript<T>(key: Key, as type: T.Type, defaultValue defaultValue: T?) -> T? {
    // the actual function is more complex than this :)
    return nil
}
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda