2016-07-30 12 views
-2

Mit Swift 2, ich habe den folgenden Code:SwiftyJSON Shuffle

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

Leider, die nicht funktionierten.

Irgendwelche Hilfe, damit es funktioniert?

+2

Woher kommt das 'Shuffle() 'Methode kommt von? Wie funktioniert es nicht? –

Antwort

1

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!) 
+1

Die Shuffling-Methoden werden wörtlich aus Antworten auf http://stackoverflow.com/questions/24026510/how-do-i-shuffle-an-array-in-swift kopiert. Sie sollten Links zu diesen Antworten für die korrekte Zuordnung hinzufügen, andernfalls gilt dies als Plagiat. Weitere Informationen finden Sie unter http://stackoverflow.com/help/referencing. –

+0

Ich entschied, welche Quelle zu zitieren ... dieser Code ist überall @MartinR. Ich habe gerade die Frage gestellt, die du verlinkt hast. – modesitt

+0

Sie haben einen Fehler in Ihrer Modifikation gemacht: 'guard count> 2' sollte' guard count> = 2' sein. –