[英]Swift return string from Array
I'm trying to get a random name from this Array as a string instead of a number. 我正在尝试从此数组中获取一个随机名称作为字符串而不是数字。
IE: 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. IE:数组通常返回0到9的随机数,我宁愿它返回0到9表示的字符串(如Preston或James),而不是数字本身。
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! 谢谢您的帮助!
You should not use arc4random()
with %
operator. 您不应将
arc4random()
与%
运算符一起使用。 That introduces a modulo bias . 这引入了模偏差 。
In Swift 4.2 and later, you should use randomElement()
: 在Swift 4.2和更高版本中,您应该使用
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: 在4.2之前的Swift版本中,您应该:
You should generally use arc4random_uniform
, not arc4random
, to eliminate modulo bias. 通常,您应该使用
arc4random_uniform
而不是arc4random
来消除模偏差。
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]
You should use arc4random
like: 您应该像这样使用
arc4random
:
let firstRandom = Int(arc4random() % 10)
let secondRandom = Int(arc4random() % 6)
var standardIdent = "First Name:\(firstName[firstRandom]) Last Name:\(lastName[secondRandom]) \n Age:\(rand())"
Even better: use arc4random_uniform
to avoid modulo bias: 更好的是:使用
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())"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.