我在从字典中选择三个随机元素时遇到问题。
我的字典代码:
query.observeSingleEvent(of: .value, with: { snapshot in
for child in snapshot.children {
let childSnap = child as! DataSnapshot
var dict = childSnap.value as! [String: Any]
}
})
最佳答案
如果键是整数,则可以使用数组。
如果您只想使用字典,那么下面提到的代码可能对您有所帮助
var namesOfPeople = [Int: String]()
namesOfPeople[1] = "jacob"
namesOfPeople[2] = "peter"
namesOfPeople[3] = "sam"
func makeList(n: Int) -> [Int] {
print(namesOfPeopleCount)
return (0..<n).map { _ in namesOfPeople.keys.randomElement()! }
}
let randomKeys = makeList(3)
您可以尝试使用较旧版本的Swift,其中不可用
let namesOfPeopleCount = namesOfPeople.count
func makeList(n: Int) -> [Int] {
return (0..<n).map{ _ in Int(arc4random_uniform(namesOfPeopleCount)
}
关于swift - 如何在Swift 4.1中从字典中挑选三个随机元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52634916/