I have a class like this:
class SomeRequest: Hashable {
let parameter: String
init(parameter: String) {
self.parameter = parameter
}
var hashValue: Int {
return parameter.hashValue
}
}
Than I try to set value to dictionary by key, where key is SomeRequest:
let request = SomeRequest(parameter: "Some")
let dictionary: [SomeRequest: Any] = [:]
dictionary[request] = ...
After all this I get this error: "use of unimplemented initializer 'init()' for class"
What could be the problem?
Swift 4.2 has changed the protocol Hashable. You can see new func:
public func hash(into hasher: inout Hasher)
The reason of crash, that hash(into: ) call SomeRequest.init(). You can say: Hey, i don't adopt hash(into: ) method! But swift does behind the scene.
For fix that you need implement hash(into:) :
class SomeRequest: Hashable {
let parameter: String
init(parameter: String) {
self.parameter = parameter
}
func hash(into hasher: inout Hasher) {
hasher.combine(self.parameter)
}
}
Now, you can remove vashValue. It's calculated by hash(into:) automatically.