Shane D Shane D - 1 year ago 68
Swift Question

Implementing generic structs conforming to Hashable protocol. Error : Refernce to generic type 'strA' requires arguments in <...> error

I am trying to implement a generic struct which conforms to protocol Hashable.

struct strA<T: Equatable>:Hashable, CustomStringConvertible {
private(set) var key: String
private(set) var value: T
private(set) var timeStamp: NSDate

init(leafKey key:String, leafValue value:T){
self.key = key
self.value = value
self.timeStamp = NSDate()

var description: String {
return "\(self.key): \(self.value)"

var hashValue: Int {
return self.key.hashValue

func == (lhs: strA, rhs: strA) -> Bool {
return lhs.key == rhs.key

I get a compile error at the implementation of the equality method.
enter image description here

I have to make the struct conform to protocol Hashable because it goes inside an array, and its generic because the value can be of any of the Equatable types. ( Am not using 'Any' here because that will take almost everything. )

How do I carry forward with this situation or is there any alternative way to solve this ?

p.s. This is not a duplicate question.

Answer Source

Because strA is a generic, then the equality method must also be a generic.

func ==<T>(lhs: strA<T>, rhs: strA<T>) -> Bool {
    return lhs.key == rhs.key


Side note: All types should begin with a capital letter. So, StrA not strA.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download