2016-07-30 121 views
-2

使用斯威夫特2,我有以下代碼:SwiftyJSON洗牌

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

不幸的是,沒有工作。

任何幫助,使其工作?

+2

哪裏的'洗牌()'方法從哪裏來?它如何「不起作用」? –

回答

1

相信隨着SwiftyJSON得到一個JSON對象以迅速數組類型,你應該做的

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

你擴展數組類,以便在首位洗牌方法?如果沒有,你可以做這樣的事情

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。差異:If聲明更改爲guard

然後,您可以做這樣的事情

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

或者如果你是好使用的是iOS 9 API,您可以執行以下操作無需任何擴展:

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

洗牌方法逐字從答案複製到http://stackoverflow.com/questions/24026510/how-do-i-shuffle-an-array-in-swift。您應該爲這些答案添加鏈接以獲取正確的歸屬,否則將被視爲抄襲。有關更多信息,請參閱http://stackoverflow.com/help/referencing。 –

+0

我正在決定引用哪個源代碼... @MartinR。我只是選擇了你所關聯的問題。 – modesitt

+0

您在修改時犯了一個錯誤:'guard count> 2'應該是'guard count> = 2'。 –