简体   繁体   English

无法随机选择数组Swift的元素

[英]unable to random pick a element for the array Swift

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

}

I was trying to randomly pick an element out from the array name nameList , but when I run the program and print the randomIndex , after first time I press the button it will always return last element in the array. 我试图从数组名称nameList随机选择一个元素,但是当我运行程序并打印randomIndex ,第一次按下按钮后,它将始终返回数组中的最后一个元素。

If I exit the simulator and run it again, when I press the button it will return me fatal error Array Index is out of range . 如果我退出模拟器并再次运行它,当我按下按钮时,它将返回fatal error Array Index is out of range Is there somethings wrong with my code, why am I not able to make it randomly select an element from my array? 我的代码有什么问题吗,为什么我不能让它从我的数组中随机选择一个元素?

Your setValues() function always replaces the entire array with the last name entered. 您的setValues()函数始终用输入的姓氏替换整个数组。 That's why it seems to return the last value. 这就是为什么它似乎返回最后一个值。

you probably meant to use nameList.append(enterName.text!) in it. 您可能打算在其中使用nameList.append(enterName.text!)。

The crash upon starting may occur because nameList has not yet received a name and arc4random_uniform is being called with a parameter value of zero 启动时可能会发生崩溃,因为nameList尚未收到名称,并且用参数值零调用arc4random_uniform

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM