简体   繁体   中英

How to make Array<Any> equatable?

I have a following decodable class:

class Sample: Decodable {
    var something: Array<Any>?
}

extension Sample: Equatable {
    static func == (lhs: Sample, rhs: Sample) -> Bool {
        return rhs.something ?? [] == lhs.something ?? []
    }
}

Gives me the error type Any does not conform to the protocol.

For everyone information the object type in Array will be determined only at runtime once I receive response.

Need help.

You can not make Array<Any> as Equatable or Decodable because both protocols will need the Array's Element type to be Equatable or Decodable and Any does not fulfill this requirement.

What you can do is, create your own custom class to fulfill the above requirements as below,

class MyAny: Equatable, Decodable {

    static func == (lhs: MyAny, rhs: MyAny) -> Bool {
        return lhs.id == rhs.id
    }

    var id: Int
}

class Sample: Decodable {

    var something: Array<MyAny>?
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM