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

228
Visualizações
Can a swift switch be exhaustive for type Double without a default case?

Can a swift switch be exhaustive for type Double without a default case?

This switch (without a default case) gives the error: switch must be exhaustive:

    var minY = 1.0

    switch minY {
    case -(Double.infinity)..<0.9:
        yAxisMinimum = 0.0
    case (0.9..<0.99):
        yAxisMinimum = 0.9
    case (0.99..<0.999):
        yAxisMinimum = 0.99
    case (0.999..<0.9999):
        yAxisMinimum = 0.999
    case (0.9999...Double.infinity):
        yAxisMinimum = 0.9999
    }

But this switch, with the (useless) default case, works:

    var minY = 1.0

    switch minY {
    case -(Double.infinity)..<0.9:
        yAxisMinimum = 0.0
    case (0.9..<0.99):
        yAxisMinimum = 0.9
    case (0.99..<0.999):
        yAxisMinimum = 0.99
    case (0.999..<0.9999):
        yAxisMinimum = 0.999
    case (0.9999...Double.infinity):
        yAxisMinimum = 0.9999
    default:
        yAxisMinimum = 0.0
    }

I try to avoid default cases with my switches, but don't know if that's possible with a Double.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

No because only enum types can be exhaustively checked.

But in this case, the problem is even deeper. Even if Integers could be exhaustively checked, you still couldn't exhaustively check Double without a where clause. One of the options is .nan ("not a number"), which you're not considering. So you might think to just add that case:

case .nan:
    yAxisMinimum = .nan

Not only won't this make it exhaustive, it won't even work the way you'd expect.

var minY = Double.nan

switch minY {
case -(Double.infinity)..<0.9:
    yAxisMinimum = 0.0
// ...
case .nan:
    yAxisMinimum = .nan
default:
    yAxisMinimum = 0
}

yAxisMinimum // 0

Why? Because of this:

var minY = Double.nan
minY == .nan   // false

NaN is unequal to everything, including NaN. So there's no way to include it directly in a switch statement. You have to use a where clause:

case _ where minY.isNaN:
    yAxisMinimum = .nan

And that's definitely beyond the compiler's ability to validate.

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