Home > Software design >  How can i get a specific element of a collection with specific id in SwiftUI?
How can i get a specific element of a collection with specific id in SwiftUI?

Time:11-27

I have a function where i pass a collection (reversed) of Messages with an ID. How can i get the specific message corresponding to this ID?

My Struct :

import Foundation
import FirebaseFirestoreSwift

struct Message_M: Codable, Identifiable, Hashable {
    @DocumentID var id: String?
    var msg: String
    var dateCreated: Date
    var userFrom: String
    ...

    enum CodingKeys: String, CodingKey {
        case id
        case msg
        case dateCreated
        case userFrom
        ...
    }
}

I want to do something like this... messages(@DocumentID: ID).userFrom is not working here and i don't know how to get the correct syntax.

    func checkRead(from: String, messages: ReversedCollection<[Message_M]>, ID: String) {

        if currentUserID != messages(@DocumentID: ID).userFrom {
            
         // Do something here...

        }
    }

CodePudding user response:

Here is a way for you:

func checkRead(from: String, messages: ReversedCollection<[Message_M]>, ID: String) {

    if let message: Message_M = messages.first(where: { element in element.id == ID }) {
        print(message.msg)
    }
}
  • Related