Hi I’m trying to shuffle an array which I can then use in all my IBAction functions thereafter in the order that I shuffled them. Example of code which is the same idea as what I have…
Class ViewContoller: UIViewContoller
Let numbers = [1,2,3,4,5]
override func viewDidLoad() {
super.viewDidLoad() }
I’ve tried to write a function here to create an array which has been shuffled so I can use that shuffled array …
func shuffledArray() -> Array<Int> {
let numbersArray = numbers.shuffled()
return numbersArray }
let myListOfShuffledNumbers = shuffledArray()
Now this works in playground.. but when I try this my viewcontroller.swift I get error ‘cannot use instance member ‘shuffledArray’ within property initializer; property initializers run before self is available.
So I know if I’m in a IBAction func I can run the function let shuffledNumbers = shuffledArray()
and get an Array of shuffled numbers to use but my problem is I need to use that same shuffle order in another IBAction function. So how can I make a universal array of shuffled numbers to use anywhere on my view controller.
I’ve tried lazy var myListOfShuffledNumbers = shuffledArray()
This gets rid of my error but it doesn’t help me because I get a 2 different list order when I use ‘myListOfShuffledNumbers’ in 2 different IBAction functions
What can I do ?? Thanks
2
Answers
You can define a property that you can access from anywhere in your
ViewContoller
, like this:At first,
myListOfShuffledNumbers
is still an empty array ofInt
s. But inside your firstIBAction
, you can assign that tounshuffledNumbers.shuffled()
. Then, you can access it from inside your secondIBAction
.Also it might be easier to just write
[Int]
instead ofArray<Int>
— they are the same thing.If you want an array that is shuffled then just convert it to a set. Sets will not keep the original order of the array.