Ich glaube, dass mit SwiftyJSON
ein JSON
Objekt an den Array-Typ in swift bekommen Sie
tun sollten,
datas["products"].array or datas["products"].arrayValue
erweitern Sie die Array-Klasse eine Shuffle-Methode in erster Linie zu haben? Wenn nicht, könnten Sie so etwas wie dieses
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 tun. Unterschiede: If
Anweisung geändert zu guard
.
Sie könnten dann tun so etwas wie dieses
let shuffled = (datas["products"].array!).shuffle()
Oder wenn Sie in Ordnung mit iOS 9 APIs sind, können Sie die folgenden ohne Erweiterungen tun:
let shuffled = GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(datas["products"].array!)
Woher kommt das 'Shuffle() 'Methode kommt von? Wie funktioniert es nicht? –