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

181
Visualizações
Need explanation about random function swift

Got a question about my random function: why is it giving this error?

'4294967295' is not exactly representable as 'Float'; it becomes '4294967296'

-

my code is

func random() ->CGFloat {
    return CGFloat(Float(arc4random()) / 0xFFFFFFFF)
}
func  random(min: CGFloat, max: CGFloat) -> CGFloat {
    return random() * (max - min) + min
}

it doesn't change the functionality of the application but it just appeared out of nowhere.

thanks in advance!

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

0

A IEEE 754 32-bit floating point number has 24 significant bits for the mantissa, that is not enough to store a 10-digit integer exactly:

print(0xFFFFFFFF)             // 4294967295
print(Float(0xFFFFFFFF))      // 4.2949673e+09
print(Int(Float(0xFFFFFFFF))) // 4294967296

That won't affect your code because

Float(arc4random()) / Float(0xFFFFFFFF)

is still a floating point number between 0.0 and 1.0. Changing the calculation to

return CGFloat(arc4random()) / 0xFFFFFFFF

will fix the warning on 64-bit platforms: The integer constant is now converted to a (64-bit) Double.

But as of Swift 4.2 you can avoid the problem completely by using the new Random API:

func random(min: CGFloat, max: CGFloat) -> CGFloat {
    return CGFloat.random(in: min...max)
}
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