我试图从这个数组中获取一个随机名称作为字符串而不是数字。
I.E:数组通常会返回一个0到9的随机数,我希望它返回0到9表示的字符串,如Preston或James,而不是数字本身。
以下代码已被破解,但我希望它可以让您看到我尝试做的事情。
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)
感谢您的帮助!
答案 0 :(得分:2)
您不应将arc4random()
与%
运算符一起使用。这引入了modulo bias。
在Swift 4.2及更高版本中,您应该使用randomElement()
:
let firstNames = ["Preston", "Ally", "James", "Justin", "Dave", "Bacon", "Bossy", "Edward", "Edweird"]
let randomFirstName = firstNames.randomElement()!
或者,如果阵列可能是空的,请不要使用强制解包操作符,而是执行:
guard let randomFirstName = firstNames.randomElement() else {
print("array was empty")
return
}
在4.2之前的Swift版本中,你应该:
您通常应使用arc4random_uniform
而不是arc4random
来消除模偏差。
您应该使用数组中项目的计数来确定可能的索引值的范围。
因此:
guard firstNames.count > 0 else { ... }
let index = Int(arc4random_uniform(UInt32(firstNames.count)))
let randomFirstName = firstNames[index]
答案 1 :(得分:1)
您应该使用arc4random
之类的:
let firstRandom = Int(arc4random() % 10)
let secondRandom = Int(arc4random() % 6)
var standardIdent = "First Name:\(firstName[firstRandom]) Last Name:\(lastName[secondRandom]) \n Age:\(rand())"
答案 2 :(得分:1)
更好:使用arc4random_uniform
来避免模偏差:
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())"