SwiftyJSON 随机播放

SwiftyJSON Shuffle

使用Swift2,我有以下代码:

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()

不幸的是,那没有用。

有什么帮助让它发挥作用吗?

我相信使用 SwiftyJSONJSON 对象转换为 swift 中的数组类型你应该这样做

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

您首先要扩展数组 class 以使用随机播放方法吗?如果没有,你可以这样做

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.

然后你可以做这样的事情

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

或者,如果您可以使用 iOS 9 个 API,则可以在没有任何扩展的情况下执行以下操作:

let shuffled = GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(datas["products"].array!)