skip to Main Content

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


  1. You can define a property that you can access from anywhere in your ViewContoller, like this:

    class ViewContoller: UIViewContoller {
    
        let unshuffledNumbers = [1,2,3,4,5]
        var myListOfShuffledNumbers = [Int]() /// here! it's still empty at first
    
        @IBAction func firstButtonPressed(_ sender: Any) {
            myListOfShuffledNumbers = unshuffledNumbers.shuffled()
        }
    
        @IBAction func secondButtonPressed(_ sender: Any) {
            /// do something with myListOfShuffledNumbers here...
        }
    }
    

    At first, myListOfShuffledNumbers is still an empty array of Ints. But inside your first IBAction, you can assign that to unshuffledNumbers.shuffled(). Then, you can access it from inside your second IBAction.

    Also it might be easier to just write [Int] instead of Array<Int> — they are the same thing.

    func shuffledArray() -> [Int] { 
        let numbersArray = numbers.shuffled() 
        return numbersArray
    }
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search