我有一个数组中的项目,我希望Xcode随机选择其中一个来显示,我对编码很新,所以如果你能详细解释它会很棒。我希望它从数组中选择一个,然后选择PrintLn。这是我目前的代码。
import UIKit
class Player1: UIViewController {
var stringArray = ["string1", "string2", "string3"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func truth() {
print(stringArray.random())
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
答案 0 :(得分:-1)
您可以将此小扩展添加到Array类:
extension Array {
public func random() -> Element {
let index = Int(arc4random_uniform(UInt32(self.count)))
return self[index]
}
}
然后您可以像这样使用数组的random()
函数:
var stringArray = ["string1", "string2", "string3"]
print(stringArray.random())