Puneet
Puneet

Reputation: 35

How to create random number in swift 2

i am new to swift two and was wondering how to make a random number generator. it needs to do numbers from 1 - 5. I have tried Int(arc4random(6)) but i don't think it works in swift 2 because i always get an error message.

thank you so much for anyone that helps.

Upvotes: 0

Views: 207

Answers (2)

arled
arled

Reputation: 2690

This does it:

    // +1 to start from 1 and not 0
    let randomNumber = Int(arc4random_uniform(5) + 1)

    if randomNumber % 2 == 0 {
        print("\(randomNumber) is an even number")
    }else{
        print("\(randomNumber) is an odd number")
    }

Upvotes: 1

Matt Lewin
Matt Lewin

Reputation: 502

To accomplish what you want, you can do let number = arc4random_uniform(6) in Swift.

Upvotes: 0

Related Questions