返回数组中的前 3 个值

Returning first 3 values in a array

我有一个如下所示的数组:

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()

如您所见,该数组包含六个不同的字符串。我当前使用的代码将 return 随机添加数组中的字符串,但我只想随机 return 前 3 个字符串。我该怎么做?

您可以尝试使用

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)) 这将 return 随机 Int 值高达 3。

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"