/ / SwiftyJSON Shuffle [zatvorené] - rýchle, rýchle2

SwiftyJSON Shuffle [zatvorené] - rýchle, rýchle2

Pomocou nástroja Swift 2 mám nasledujúci kód:

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

Bohužiaľ to nefungovalo.

Akákoľvek pomoc, aby to fungovalo?

odpovede:

1 pre odpoveď č. 1

Verím, že s SwiftyJSON získať JSON objekt na typ poľa v rýchle by ste mali robiť

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

Rozširujete triedu poľa, aby ste na prvom mieste mali metódu náhodného výberu? Ak nie, tak by ste mohli niečo urobiť

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])
}
}
}

zdroj , rozdiely: If vyhlásenie zmenené na guard.

Potom by ste mohli urobiť niečo také

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

Alebo ak máte v poriadku rozhrania API pre iOS 9, môžete urobiť nasledujúce bez akýchkoľvek rozšírení:

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