Swift 快速洗牌
使用Swift 2,我有以下代码:Swift 快速洗牌,swift,swift2,Swift,Swift2,使用Swift 2,我有以下代码: 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() 不幸的是,这不起作用 有什么帮助吗?我认为使用SwiftyJSON在swift中为数组类型获取JSON对象应该是 datas["
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()
不幸的是,这不起作用
有什么帮助吗?我认为使用
SwiftyJSON
在swift中为数组类型获取JSON
对象应该是
datas["products"].array or datas["products"].arrayValue
您是否首先扩展了array类以拥有一个shuffle方法?如果不是,你可以这样做
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])
}
}
}
let shuffled = (datas["products"].array!).shuffle()
或者,如果您可以使用iOS 9 API,则无需任何扩展即可执行以下操作:
let shuffled = GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(datas["products"].array!)
洗牌方法从答案一字不差地复制到。你应该添加这些答案的链接以便正确归属,否则将被视为剽窃。有关更多信息,请参阅。我正在决定引用哪个来源。。。那个密码到处都是@MartinR。我刚刚定位了您链接的问题。您在修改中出错:
guard count>2
应该是guard count>=2
。shuffle()
方法来自哪里?它如何“不起作用”?