2014-06-10 22 views
37

ho questa espressione che restituisce un UInt32:Swift convertito UInt a int

let randomLetterNumber = arc4random()%26 

voglio essere in grado di utilizzare il numero in questo if:

if letters.count > randomLetterNumber{ 
    var randomLetter = letters[randomLetterNumber] 
} 

Questo problema è che il console mi sta dando questa

Playground execution failed: error: <REPL>:11:18: error: could not find an overload for '>' that accepts the supplied arguments 
if letters.count > randomLetterNumber{ 
    ~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~ 

Il problema è che non può UInt32 essere confrontato con un Int. Voglio trasmettere randomLetterNumber a Int. Ho provato:

let randomLetterUNumber : Int = arc4random()%26 
let randomLetterUNumber = arc4random()%26 as Int 

Questi sia causa could not find an overload for '%' that accepts the supplied arguments.

Come posso cast del valore e non utilizzarlo in if?

risposta

69

Int(arc4random_uniform(26)) fa due cose, una elimina i risultati negativi dal metodo corrente e la seconda deve creare correttamente un Int dal risultato.

+2

Grazie per questo, l'inizializzatore Int() sembra fare il trucco. – 68cherries

+3

Puoi leggere ulteriori informazioni sulla conversione del tipo numerico in ** [Documenti di Apple Swift] (https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/TheBasics.html#//apple_ref/ doc/uid/TP40014097-CH5-XID_420) **. –

+7

Grazie. Ho avuto un problema simile con arc4random_uniform (someArray.count) soluzioni di fusione il problema arc4random_uniform (UInt32 (someArray.count)) – nacross

10

basta creare un nuovo int con esso

let newRandom: Int = Int(randomLetterNumber) 
if letters.count > newRandom { 
    var randomLetter = letters[newRandom] 
} 

o se non avete mai preoccupate per l'UInt32 si può semplicemente creare un Int subito:

let randomLetterNumber = Int(arc4random() % 26) 
+0

Si noti che questo genererà un'eccezione metà del tempo a causa di overflow controllando, usa la risposta che ho dato per evitarlo. –

+0

@David, come mai? Non è in disaccordo, voglio solo capire cosa intendi. – Firo

+1

In realtà non lo fara da quando stai facendo il casting dopo il modulo, quindi puoi garantire che sia sempre nei limiti. 'Int (arc4random())' si bloccherà il 50% del tempo in cui viene eseguito su una piattaforma a 32 bit perché un UInt32 non si adatta a un Int32. Ho appena visto troppe domande "arc4random è bugged and crashes" con swift. In ogni caso arc4random_uniform darà una distribuzione più uniforme. –

8

Più semplice di così, impossibile:

Int(myUInteger) 
+0

Questo fa esattamente l'opposto di ciò che l'OP chiedeva. Dovrebbe essere 'Int (myUInteger)' – alternatiph

0

Si può fare

let u: UInt32 = 0x1234abcd 
let s: Int32 = Int32(bitPattern: u)