Compare value from two struct in swift

后端 未结 4 1525
梦毁少年i
梦毁少年i 2021-01-25 18:09

I have two struct and two arrays corresponding to it and I am trying to compare the two array values and print it in one filtered array i did try and use filter but its giving m

4条回答
  •  梦毁少年i
    2021-01-25 18:47

    your mainArray is of type [Two] and you are trying to put data of type [One] in mainArray. According to swift this is wrong you cannot do this.

    you can do it in another way let me post it in 10 mins

    You have 2 options now either make common protocol like and confirm the structs with it and make the mainArray of that protocol type as follows:

    protocol Identifiable {
        var id: String {get set}
        var name: String {get set}
        var lastName: String {get set}
    }
    
    struct One: Identifiable{
        var id: String
        var name: String
        var lastName: String
    }
    
    struct Two: Identifiable{
        var id: String
        var name: String
        var lastName: String
    }
    

    now make the main Array of type Identifiable as follows

     var mainArray = [Identifiable]()
    

    and filter as follows

     mainArray = oneData.filter{ i in twoData.contains { i.id == $0.id }}
    

    Another option is do not make the protocol Identifiable and let the structs be as they were before. And just make the mainArray of type [One] just dont forget to change the change in filter line i.e From this:

     mainArray = oneData.filter{ $0.ID == twoData.contains(where: $0.ID)}
    

    To this:

     mainArray = oneData.filter{ i in twoData.contains { i.id == $0.id }}
    

提交回复
热议问题