目标
我希望能够循环通过while循环生成随机数。每次迭代一个随机数,如果它不起作用,则另一个迭代。等等。我想从我的数据库中获得一个必须满足三个条件的随机用户。 (它们在循环的底部列出)。
挑战
如何确保我的代码按正确的顺序执行?
我们想要用户吗?
A)是的。退出while循环
B)编号。再次从1.开始。我们想要另一个用户
我的结果
static func getRandomUser(){
var randomNumberID = 1
var UID = ""
var current_user: User? = nil
let dispatchGroup = DispatchGroup()
let dispatchQueue = DispatchQueue(label: "taskQueue")
let dispatchSemaphore = DispatchSemaphore(value: 0)
dispatchQueue.async {
repeat {
dispatchGroup.enter()
// Randomly select one user
randomNumberID = Int.random(in: 1...Internet.all_time_user_count)
// Transform generated number to uid with which we can retreave the user from the database
// E.g. "1" -> "iosdnaui29pbpqwbdabd"
Internet.getUIDOfUser(with: String(randomNumberID)) { (uid) in
UID = uid
// Download user from database
Internet.getUser(with: uid) { (user) in
current_user = user
dispatchSemaphore.signal()
dispatchGroup.leave()
}
}
dispatchSemaphore.wait()
/// Stay in the loop until we find a user
/// 1. Whom we don't have yet `Internet.contains(uid: UID, in: discover_users)`
/// 2. Who exists in the database `current_user == nil`
/// 3. Who wants to be found `current_user?.discoverable == false`
} while(current_user == nil || current_user?.discoverable == false || Internet.contains(uid: UID, in: discover_users))
// I want to execute the following line of code when I know that I found an user whith the conditions of the while loop
discover_users.append(current_user!)
}
// Do I need another dispatchGroup like this which notifies me when the whole while-loop is finished?
dispatchGroup.notify(queue: dispatchQueue) {
DispatchQueue.main.async {
print("Another loop iteration finished")
}
}
}
我当前代码所基于的来源: