I've tried a lot of approaches to randomly generate an array from existing one. And one of them finally worked out for me:
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() }
}
}
}
But, for some reasons, this code works only if I put this method on the array inside of the button-action, for example:
@IBAction func generate(_ sender: UIButton) {
words.shuffle()
print (words)
}
If put exactly the same code in the viewDidLoad, nothing is sorted. So how can I sort my array without any action?
P.S. If you don't know the answer, you can recommend any other approach to generate random array. Thank You!