Каково решение ошибки «Значение типа [User] ‘не может быть преобразовано в ожидаемый тип аргумента’User»?

#ios #swift #iphone #xcode

#iOS #swift #iPhone #xcode

Вопрос:

На моей странице с именем service xcode указывает на пользователя и выдает ошибку. но это не работает. Как вы думаете, что мне следует изменить? мой пользователь уже является необязательным. Я думаю, что это проблема с индексом, но я не знаю, как ее решить, я был бы признателен, если бы вы могли помочь. как вы думаете, в чем проблема

message.swift

 import Firebase

struct Message {
    let text: String
    let toId: String
    let fromId: String
    var timestamp: Timestamp!
    var user: User?
    let isFromCurrentUser :Bool
    
    init(dictionary: [String: Any]) {
        self.text = dictionary["text"] as? String ?? ""
        self.toId = dictionary["toId"] as? String ?? ""
        self.fromId = dictionary["fromId"] as? String ?? ""
        self.timestamp = dictionary["timestamp"] as? Timestamp ?? Timestamp(date: Date())
        self.isFromCurrentUser = fromId == Auth.auth().currentUser?.uid
    }
    
    
}

struct Conversation {
    let user: User
    let message : Message
}
  

Обслуживание.Swift

 import Firebase
 
struct Service  {
    static func  fetchUsers (completion: @escaping([User]) -> Void) {
        var users = [User] ()
       COLLECTION_USERS.getDocuments { (snapshot, error) in
            snapshot?.documents.forEach({ (document) in
               
                let dictionary  = document.data()
                let user = User(dictionary: dictionary)
                users.append(user)
                completion(users)
            
            })
        }
    }
    
    static func fetchUser(widhtUid uid: String, completion:@escaping([User]) ->Void) {
        
COLLECTION_USERS.document(uid).getDocument { (snapshot, error) in
    guard let dictionary = snapshot?.data() else {return}
    let user = User(dictionary: dictionary)
    completion(user)
        }
        
        
    }
    
    
    static func fetchConversations (completion: @escaping([Conversation]) ->Void) {
        var conversations = [Conversation]()
        guard let uid = Auth.auth().currentUser?.uid else {return}
        
        let query = COLLECTION_MESSAGES.document(uid).collection("recent-messages").order(by:  "timestamp")
        query.addSnapshotListener { (snapshot, error) in
            snapshot?.documentChanges.forEach({ change in
                let dictionary = change.document.data()
                let message = Message(dictionary: dictionary)
                
                self.fetchUser(widhtUid: message.toId) { user in
                    let conversation = Conversation(user:user, message: message)
                    conversations.append(conversation)
                    completion(conversations)
                }
                
           
            })
        }
        
    }
    
    
    static func fetchMessages    (forUser user: User, completion: @escaping([Message])-> Void)  {
    var messages  = [Message]()
    guard let currentUid = Auth.auth().currentUser?.uid else {return}
        let query = COLLECTION_MESSAGES.document(currentUid).collection(user.uid).order(by: "timestamp")
        query.addSnapshotListener{(snapshot,error) in
        snapshot?.documentChanges.forEach({ change in
            if change.type == .added {
                let dictionary = change.document.data ()
                
                messages.append(Message(dictionary: dictionary))
                completion(messages)
            }
        
            
            
            
        })
    }
    }
 static func  uploadMessage(message: String, to user: User, completion: ((Error?)->Void)?) {
        guard let currentUid = Auth.auth().currentUser?.uid else {return}
        let data = ["text": message,
                    "fromId": currentUid,
                    "toId": user.uid,
                    "timestamp" : Timestamp(date: Date())] as [String : Any]
           COLLECTION_MESSAGES.document(currentUid).collection(user.uid).addDocument(data:data) { _ in
                COLLECTION_MESSAGES.document(user.uid).collection(currentUid).addDocument(data:data,completion:completion)
            
            COLLECTION_MESSAGES.document(currentUid).collection("recent- messages").document(user.uid).setData(data)
            
            COLLECTION_MESSAGES.document(user.uid).collection("recent- messages").document(currentUid).setData(data)
            
            
        }
    }
}
  

Комментарии:

1. Какая строка генерирует ошибку?

Ответ №1:

В этом методе:

 static func fetchUser(widhtUid uid: String, completion:@escaping ([User]) -> Void)
  

Параметр завершения закрытия должен быть a User , а не массив пользователей — [User] .

Комментарии:

1. Вы говорите, что это правда, это исправило эту ошибку. Спасибо

Ответ №2:

Xcode должен указать вам строку, в которой возникает эта ошибка…

В любом случае, здесь

 static func fetchUser(widhtUid uid: String, completion:@escaping([User]) ->Void) {
        
COLLECTION_USERS.document(uid).getDocument { (snapshot, error) in
    guard let dictionary = snapshot?.data() else {return}
    let user = User(dictionary: dictionary)
    completion(user)
        }
        
        
    }
  

Ваш completion:@escaping([User]) ->Void) ожидает массив [User] , но вы вызываете его только с одним User объектом здесь completion(user)

Комментарии:

1. Верно… Я не нашел противоположного случая, так что, возможно, это опечатка вопроса 🙂

2. да, я понял, я нашел свою ошибку, благодаря пользователь не является строкой пользователя, исправлена при удалении из массива