简体   繁体   中英

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.

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 . 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. That's why it seems to return the last value.

you probably meant to use nameList.append(enterName.text!) in it.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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