import UIKit
class ViewController: UIViewController {
@IBOutlet var Text1: UITextField!
@IBOutlet var Text2: UITextField!
@IBOutlet var Text3: UITextField!
@IBOutlet var Label: UILabel!
let array = ["Frodo", "sam", "wise", "gamgee"]
let randomIndex = Int(arc4random_uniform(UInt32(array.count))) //Problem is here
@IBAction func button(_ sender: Any) {
Label.text = array[randomIndex]
}
}
Asked
Active
Viewed 27 times
0

vadian
- 274,689
- 30
- 353
- 361

Sonny Sluiter
- 139
- 2
- 9
-
Possible duplicate of [How to initialize properties that depend on each other](https://stackoverflow.com/questions/25854300/how-to-initialize-properties-that-depend-on-each-other) – vadian Jan 22 '18 at 09:02
2 Answers
0
You didn't ask any question so I assume you have problem with accessing count
of array
.
In general you can't access any of instance members until init is completed. There are (at least) three solutions for your problem.
First is to override all init
required by UIViewController and set randomIndex
there.
Second is to use lazy
for randomIndex
:
lazy var randomIndex = {
Int(arc4random_uniform(UInt32(array.count)))
}()
Third is to use some model (class/struct) for those data and inject it to ViewController

Mateusz
- 1,222
- 11
- 22
0
You cannot run the line to get the random index on the top level of the class.
It must be located within a function / method:
@IBAction func button(_ sender: Any) {
let randomIndex = Int(arc4random_uniform(UInt32(array.count)))
Label.text = array[randomIndex]
}
And please conform to the naming convention that variable names start with a lowercase letter (text1
, label
).

vadian
- 274,689
- 30
- 353
- 361