我有一个如下所示的数组:
var myArray = ["1one", "1two", "1three", "1four", "1five", "1six"]
为了得到随机,我用这个:
var originalNames = [String]()
func getRandomName() -> String {
if (names.count == 0) {
names = originalNames
}
let randomNumber = Int(arc4random_uniform(UInt32(names.count)))
return names.removeAtIndex(randomNumber)
}
我这样使用它:
self.randomLabel.text = getRandomName()
如您所见,该数组包含六个不同的字符串。我目前使用的代码将返回随机添加数组内的字符串,但我只想随机返回前3个字符串。我怎么能这样做?
答案 0 :(得分:2)
您可以尝试使用
var originalNames = [String]()
func getRandomName() -> String {
if (names.count == 0) {
names = originalNames
}
let randomNumber = Int(arc4random_uniform(3))
return names[randomNumber]
}
所以let randomNumber = Int(arc4random_uniform(3))
这会将随机Int
值返回到3。
答案 1 :(得分:1)
var myArray = ["1one", "1two", "1three", "1four", "1five", "1six"]
var result:[String] = []
while result.count < 3 {
let randomNumber = Int(arc4random_uniform(UInt32(myArray.count)))
result.append(myArray.removeAtIndex(randomNumber))
}
print(result) // "["1two", "1one", "1three"]\n"
如果您不想修改原始数组,只需复制一份
let myArray = ["1one", "1two", "1three", "1four", "1five", "1six"]
var inputNames = myArray
var result:[String] = []
while result.count < 3 {
result.append(inputNames.removeAtIndex(Int(arc4random_uniform(UInt32(inputNames.count)))))
}
print(result) // "["1six", "1two", "1one"]\n"