-2

Using Swift 2, I have the following code:

var datas = SwiftyJSON.JSON(json)

// now datas has products. I need to shuffle products and get them in random order

datas["products"] = datas["products"].shuffle()

Unfortunately, that didn't work.

Any help to make it work?

Hamid
  • 289
  • 1
  • 5
  • 12

1 Answers1

1

I believe that with SwiftyJSON to get a JSON object to the array type in swift you should be doing

datas["products"].array or datas["products"].arrayValue

Are you extending the array class to have a shuffle method in the first place? If not, you could do something like this

extension CollectionType {
    /// Return a copy of `self` with its elements shuffled
    func shuffle() -> [Generator.Element] {
        var list = Array(self)
        list.shuffleInPlace()
        return list
    }
}

extension MutableCollectionType where Index == Int {
    /// Shuffle the elements of `self` in-place.
    mutating func shuffleInPlace() {
        // empty and single-element collections don't shuffle
        guard count >= 2 else { return }
        for i in 0..<count - 1 {
            let j = Int(arc4random_uniform(UInt32(count - i))) + i
            guard i != j else { continue }
            swap(&self[i], &self[j])
        }
    }
}

Source . Differences: If statement changed to guard.

You could then do something like this

let shuffled = (datas["products"].array!).shuffle()

Or if you are okay using iOS 9 APIs, you can do the following without any extensions:

let shuffled = GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(datas["products"].array!)
Community
  • 1
  • 1
modesitt
  • 7,052
  • 2
  • 34
  • 64
  • 1
    The shuffling methods are copied verbatim from answers to http://stackoverflow.com/questions/24026510/how-do-i-shuffle-an-array-in-swift. You should add links to those answers for proper attribution, otherwise it is considered plagiarism. See http://stackoverflow.com/help/referencing for more information. – Martin R Jul 30 '16 at 21:12
  • I was deciding which source to quote... that code is all over the place @MartinR. I just sited the question you linked. – modesitt Jul 30 '16 at 21:18
  • You made an error in your modification: `guard count > 2` should be `guard count >= 2`. – Martin R Jul 31 '16 at 00:10