Shuffling array Xcode 8.2

Hi Everyone,

I am coding an older mac and am struggling to .shuffle my cards numbers in Xcode 8.2

Would anyone be able to help me out?

This is for the card game (matching pairs) - lesson 4.

Thanks :slight_smile:

Hi Brett,

Welcome to the Code Crew community.

So what you are saying is that array.shuffle() is not available?

Hi Chris,

Sorry for not being more specific, yes .shuffle does not work. I believe it’s not a part of this Xcode (although could be wrong).

If you have any suggestions on how to do this without that function, that would be great.

Thanks

BH

What version of Mac Operating System are you using? Tap on the Apple symbol and select “About this Mac”. Post a screen shot of that in a reply.

You may be able to install a later version of Xcode depending on the version of MacOS.

Hi Chris,

Thanks for getting back to me, Unfortunately I am not the only mac user on this computer, and the other user has requested I don’t update the OS. However,
Here is the screenshot of my OS version.

Thank you for taking the time to offer you help.

BH

Looks like you are limited to Xcode 8.2 which is what you have.

I found this on GItHub. I have no idea how effective it is so maybe give it a shot. Create a new Swift file in your Xcode project and add this code to it.

import Foundation

extension Array {
    /** Randomizes the order of an array's elements. */
    mutating func shuffle() {
        for _ in 0..<10 {
            sort { (_,_) in arc4random() < arc4random() }
        }
    }
}

Then in your code you can say array.shuffle() which will do the same thing as the built in .shuffle() method in later versions of Xcode.

Thanks for sending this through, I will give it a go this evening and let you know how it goes.
Fingers crossed, thank you for sourcing this for me!

Hi Bh89,

I have the same issue as you do ( I am using Xcode 9, swift 4.1)
have you finally succeed to get this shuffle array ?

@couvid welcome to the community!

You can view the docs of any Apple function. Here’s the one for shuffle

You can use it with iOS 8.0+, iPadOS 8.0+, macOS10.10+, tvOS 9.0+ and watchOS 2.0+

Doing some more digging, because Swift is open source, you can find that .shuffle() was implemented in Swift 4.2

From this proposal

Hi Mikaelacaron,

Thanks for your answer,

This shuffle() function is for version 4.2. Seems different in 4.1.

Yes it probably is, considering the shuffle I linked was implemented in 4.2

@couvid

Did you try the extension in the 6th post in this thread?