2016-07-30 118 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'。 –