1

I have a struct called Survey. It conforms to both Equatable and Hashable protocols.

import Foundation

public struct Survey {
    public let id: String
    public let createdAt: Date
    public let updatedAt: Date
    public let title: String
    public let type: String
}

extension Survey: Equatable { }

public func ==(lhs: Survey, rhs: Survey) -> Bool {
    return lhs.id == rhs.id && lhs.createdAt == rhs.createdAt && lhs.updatedAt == rhs.updatedAt && lhs.title == rhs.title && lhs.type == rhs.type
}

extension Survey: Hashable {
    public var hashValue: Int {
        return id.hashValue ^ createdAt.hashValue ^ updatedAt.hashValue ^ title.hashValue ^ type.hashValue
    }
}

I can get the hash value of individual Survey objects.

But how do I get the hash value of an array containing multiple Survey objects?

5
  • Firstly, you can simply do public struct Survey: Hashable and get rid of everything else (except the struct variables ofcourse) Commented Apr 27, 2018 at 11:19
  • 2
    Synthesizing Hashable conformance for arrays is implemented in Swift 4.2: github.com/apple/swift-evolution/blob/master/proposals/… Commented Apr 27, 2018 at 11:20
  • Secondly, what do you mean get the hash value of an array containing multiple Survey objects. Include the expected code that you would like to achieve for this. Something like [survey_1, survey_N].hashValue? Commented Apr 27, 2018 at 11:20
  • @staticVoidMan yes, that's right. Commented Apr 27, 2018 at 11:29
  • @Isuru Then @Tj3n's answer has you covered for Swift 4.1. Commented Apr 27, 2018 at 11:31

1 Answer 1

2

Maybe something like this?

extension Array: Hashable where Iterator.Element: Hashable {
    public var hashValue: Int {
        return self.reduce(1, { $0.hashValue ^ $1.hashValue })
    }
}

Custom hash value is just value you define anyway

*Edit: This would also work if you only want Hashable for Survey array

extension Array: Hashable where Element == Survey {
    public var hashValue: Int {
        return self.reduce(1, { $0.hashValue ^ $1.hashValue })
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

you can actually reduce that to extension Array where Element: Hashable
@staticVoidMan I think the OP want to do something with the Array that must conform Hashable (like using NSOrderedSet), so I think its good to keep it
Noted! My bad :) Extend Array to conform to Hashable explictly and use the where condition appropriately.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.