Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

139
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda