Reputation: 589
In TerningspilletSpillereViewController
I have an array that looks like this:
var mineSpillere = ["1SP", "2SP", "3SP"]
and this under:
func assignArray() {
let obj = TerningspilletViewController()
obj.mineSpillere2 = self.mineSpillere
}
In my other UIViewController
(TerningspilletViewController
) I have this
var mineSpillere2 = [String]()
I want to generate a random (1SP, 2SP or 3SP) on button click like this from a function:
func generateNumber() {
let array = aBB
let randomIndex = Int(arc4random_uniform(UInt32(array.count)))
randomLabel.text = (array[randomIndex])
}
But this gives me the following error:
fatal error: Array index out of range.
I this line randomLabel.text = (array[randomIndex])
Why is that?
Upvotes: 1
Views: 4821
Reputation: 32597
That error could occur for two reasons:
array.count
and the array access. This could only happen if you assign or modify the array from another threadarc4random_uniform
can never produce a number 0<=X<0
(and whatever it returns will trigger an index-out-of-bounds exception).So if you are not using multiple threads, check if the array is empty.
Upvotes: 0
Reputation: 6800
See this example and update for your usage. I'm not quite understanding your naming but this is how you can get the data from a different view controller (that is initialized with the data).
First View Controller:
import UIKit
class ViewController: UIViewController {
var arrayWithoutData = [String]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
assignArray()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func assignArray() {
let otherVC = NextViewController()
arrayWithoutData = otherVC.mineSpillere
println(arrayWithoutData)
}
}
Second View Controller:
import UIKit
class NextViewController: UIViewController {
var mineSpillere = ["1SP","2SP","3SP"]
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.
}
/*
// 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.
}
*/
}
Upvotes: 2