随机生成的数组仅适用于按钮

时间:2017-08-05 19:14:37

标签: ios arrays swift sorting

我尝试过很多方法从现有数组中随机生成一个数组。其中一个终于为我解决了:

    extension Array {
    mutating func shuffle() {
// get data from my FireBase and calculate amount of items in it
        var ref: DatabaseReference?
        var databaseHandle: DatabaseHandle?
        var words = [lWord]()
        ref = Database.database().reference()
            guard let uid = Auth.auth().currentUser?.uid else {
                print ("smt wrong with user uid")
                return
            }
           databaseHandle = ref?.child("Users").child(uid).child("LearningNow").observe(.value, with: { (snapshot) in
                var newItems: [lWord] = []
                for item in snapshot.children {
                    let wordItem = lWord(snapshot: item as! DataSnapshot)
                    newItems.append(wordItem)
                }
                words = newItems
            })
        let count = words.count + 1
        for _ in 0..<count  {
            sort { (_,_) in arc4random() < arc4random() }
        }
    }
}

但是,由于某些原因,只有当我将此方法放在button-action内部的数组上时,此代码才有效,例如:

@IBAction func generate(_ sender: UIButton) {
    words.shuffle()
    print (words)
}

如果在viewDidLoad中放置完全相同的代码,则不会对任何内容进行排序。那么如何在没有任何动作的情况下对数组进行排序

P.S。如果您不知道答案,可以推荐任何其他方法来生成随机数组。谢谢!

1 个答案:

答案 0 :(得分:0)

感谢您的回复!我找到了解决方案,我不得不替换我的方法(代码来自this问题):

extension Array {
/// Returns an array containing this sequence shuffled
var shuffled: Array {
    var elements = self
    return elements.shuffle()
}
/// Shuffles this sequence in place
@discardableResult
mutating func shuffle() -> Array {
    indices.dropLast().forEach {
        guard case let index = Int(arc4random_uniform(UInt32(count - $0))) + $0, index != $0 else { return }
        swap(&self[$0], &self[index])
    }
    return self
}
var chooseOne: Element { return self[Int(arc4random_uniform(UInt32(count)))] }
func choose(_ n: Int) -> Array { return Array(shuffled.prefix(n)) }
}

正如您所看到的,我不会从FireBase中检索此方法的数据。所以,问题可能就在那里。