@IBOutlet weak var enterName: UITextField!
@IBOutlet weak var presentName: UITextView!
@IBOutlet weak var independceStatue: UITextField!
@IBOutlet weak var driverSelection: UITextField!
var entity : [Entity] = []
var nameList : [String] = []
var period1 = ""
var counting = 0
override func viewDidLoad() {
super.viewDidLoad()
let context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
let request = NSFetchRequest(entityName: "Entity")
var results : [AnyObject]?
do{
results = try context.executeFetchRequest(request)
} catch {
results = nil
}
if results != nil {
self.entity = results as! [Entity]
}
if !entity.isEmpty{
presentName.text = entity.last?.period1Core
}
}
func setValues() {
nameList = [enterName.text!]
}
@IBAction func setName(sender: UIButton) {
setValues()
for item in nameList{
period1 += (item + " ")
}
presentName.text = period1
enterName.text = ""
}
@IBAction func start(sender: UIButton) {
let context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
let entity = NSEntityDescription.insertNewObjectForEntityForName("Entity", inManagedObjectContext: context) as! Entity
entity.period1Core = presentName.text
do {
try context.save()
print("Item Saved")
} catch _ {
print("Saved Failed")
}
**Problem ->** let randomIndex = Int(arc4random_uniform(UInt32(nameList.count)))
driverSelection.text! = nameList[randomIndex]
print(randomIndex)
}
我试图从数组名称nameList
中随机挑选一个元素,但是当我运行程序并打印randomIndex
时,在我第一次按下按钮后它将始终返回数组中的最后一个元素。
如果我退出模拟器并再次运行它,当我按下按钮时,它将返回 fatal error 数组索引超出范围
。我的代码有问题吗?为什么我无法让它从数组中随机选择一个元素?
最佳答案
您的 setValues() 函数始终用输入的姓氏替换整个数组。这就是为什么它似乎返回最后一个值。
您可能想在其中使用 nameList.append(enterName.text!) 。
启动时可能会发生崩溃,因为 nameList 尚未收到名称,并且使用参数值 0 调用 arc4random_uniform
关于arrays - 无法为数组 Swift 随机选择一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34867093/