我正在使用Swift 3和Firebase制作一个iOS应用程序。我一直得到错误“无法将'UserFile'类型的值转换为预期的参数'User'”。这是我的代码:
import Foundation
import Firebase
import FirebaseAuth
class UserAPI {
var REF_USERS = Database.database().reference().child("users")
var CURRENT_USER: User? {
if let currentUser = Auth.auth().currentUser {
return currentUser
}
return nil
}
var CURRENT_USER_ID = Auth.auth().currentUser?.uid
var REF_CURRENT_USER: DatabaseReference? {
guard let currentUser = Auth.auth().currentUser else {
return nil
}
return REF_USERS.child(currentUser.uid)
}
func observeCurrentUser(completion: @escaping (User) -> Void) {
guard let currentUser = Auth.auth().currentUser else {
return
}
REF_USERS.child(currentUser.uid).observeSingleEvent(of: .value, with: { snapshot in
if let postDictionary = snapshot.value as? [String: Any] {
let user = UserFile.transformUser(postDictionary: postDictionary)
completion(user) //Cannot convert value of type 'UserFile' to expected argument 'User'
}
})
}
func observeUser(withID uid:String, completion: @escaping (User) -> Void) {
REF_USERS.child(uid).observeSingleEvent(of: .value, with: { snapshot in
if let postDictionary = snapshot.value as? [String: Any] {
let user = UserFile.transformUser(postDictionary: postDictionary)
completion(user) //Cannot convert value of type 'UserFile' to expected argument 'User'
}
})
}
}
“UserFile”是另一个Swift文件,其代码如下:
import Foundation
class UserFile {
var email: String?
var profileImageURL: String?
var username: String?
}
extension UserFile {
static func transformUser(postDictionary: [String: Any]) -> UserFile {
let user = UserFile()
user.email = postDictionary["email"] as? String
user.profileImageURL = postDictionary["profileImageURL"] as? String
user.username = postDictionary["username"] as? String
return user
}
}
我不知道该怎么办。有什么想法吗?
最佳答案
您的函数显示completion的类型是user:func observeCurrentUser(completion: @escaping (User) -> Void) {
,并且您正在将UserFile
传递给它。
将完成类型更改为UserFile
,如下所示:(completion: @escaping (UserFile) -> Void)