Swift convert UInt to Int

IntegerSwiftUint32

Integer Problem Overview


I have this expression which returns a UInt32:

let randomLetterNumber = arc4random()%26

I want to be able to use the number in this if statement:

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

This issue is that the console is giving me this

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

The problem is that UInt32 cannot be compared to an Int. I want to cast randomLetterNumber to an Int. I have tried:

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

These both cause could not find an overload for '%' that accepts the supplied arguments.

How can I cast the value or use it in the if statement?

Integer Solutions


Solution 1 - Integer

Int(arc4random_uniform(26)) does two things, one it eliminates the negative results from your current method and second should correctly creat an Int from the result.

Solution 2 - Integer

More simple than this, impossible:

Int(myUInteger)

Solution 3 - Integer

Just create a new int with it

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

or if you never care about the UInt32 you can just create an Int immediately:

let randomLetterNumber = Int(arc4random() % 26)

Solution 4 - Integer

You can do

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Question67cherriesView Question on Stackoverflow
Solution 1 - IntegerDavid BerryView Answer on Stackoverflow
Solution 2 - IntegerJoshView Answer on Stackoverflow
Solution 3 - IntegerFiroView Answer on Stackoverflow
Solution 4 - IntegerapplequistView Answer on Stackoverflow