【发布时间】:2019-01-28 00:53:20
【问题描述】:
你好,我需要一些关于函数和或可能在该函数中的闭包的帮助。我希望我的函数检查 firestore 用户集合中的重复文档(用户名)。如果找到重复项,我想显示一条消息,如果未找到重复项,则创建一个新用户。我有以下代码:
func checkIfUserExists(username: String, completion: @escaping (Bool) -> Void) {
let docRef = db.collection("users").document(username)
docRef.getDocument { (document, error) in
if error != nil {
print(error)
} else {
if let document = document {
if document.exists {
completion(true)
} else {
completion(false)
}
}
}
}
}
我调用函数:
if let username = textField.text, username.count > 8 { // Username needs to be more then 8 Char
checkIfUserExists(username: username) { (doesExist) in
if doesExist {
print("user exists")
} else {
print("new User can be created")
}
}
} else {
print("Username needs to be more then 8 char")
}
}
它有效,但我觉得这不是好的做法,我正在走弯路。这是正确的做法吗?
【问题讨论】:
标签: swift function firebase closures google-cloud-firestore