1

I'm trying to get a random name from this Array as a string instead of a number.

I.E: The array normally returns a random number 0 through 9, I'd rather have it return the string that 0 through 9 represents like Preston or James instead of the number itself.

The code below is broken, but I hope it lets you see what I'm trying to do.

 var firstName : [String] = ["Preston", "Ally", "James", "Justin", "Dave", "Bacon", "Bossy",     "Edward", "Edweird" ]

var standardIdent = "First Name:\(firstName[random(0...9)]) Last Name:\(lastName[random(0...5)]) \n Age:\(rand())"
println(standardIdent)

Thank you for your help!

3 Answers 3

2

You should not use arc4random() with % operator. That introduces a modulo bias.

In Swift 4.2 and later, you should use randomElement():

let firstNames = ["Preston", "Ally", "James", "Justin", "Dave", "Bacon", "Bossy", "Edward", "Edweird"]
let randomFirstName = firstNames.randomElement()!

Or, if the array could possibly be empty, don't use the forced unwrapping operator, but instead do:

guard let randomFirstName = firstNames.randomElement() else {
    print("array was empty")
    return
}

In Swift versions prior to 4.2, you should:

  1. You should generally use arc4random_uniform, not arc4random, to eliminate modulo bias.

  2. You should probably use the count of the items in the array to determine the range of possible index values.

Thus:

guard firstNames.count > 0 else { ... }
let index = Int(arc4random_uniform(UInt32(firstNames.count)))
let randomFirstName = firstNames[index]
Sign up to request clarification or add additional context in comments.

Comments

1

You should use arc4random like:

let firstRandom = Int(arc4random() % 10)
let secondRandom = Int(arc4random() % 6)
var standardIdent = "First Name:\(firstName[firstRandom]) Last Name:\(lastName[secondRandom]) \n Age:\(rand())"

Comments

1

Even better: use arc4random_uniform to avoid modulo bias:

var firstName : [String] = ["Preston", "Ally", "James", "Justin", "Dave", "Bacon", "Bossy", "Edward", "Edweird" ]

var lastName : [String] = ["Miller", "Jones", "Jackson", "Smith"]

let firstRandom = Int(arc4random_uniform(UInt32(firstName.count)))
let secondRandom = Int(arc4random_uniform(UInt32(lastName.count)))
var standardIdent = "First Name:\(firstName[firstRandom]) Last Name:\(lastName[secondRandom]) \n Age:\(rand())"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.