Assume I have a protocol like
protocol TypedString : CustomStringConvertible, Equatable, Hashable { }
func == <S : TypedString, T : TypedString> (lhs : T, rhs : S) -> Bool {
return lhs.description == rhs.description
}
I want to be able to provide a default implementation of Hashable
:
extension TypedString {
var hashValue = { return self.description.hashValue }
}
But the problem is that I get an error Use of unresolved identifier self
.
How do I create a default implementation of Hashable
using the string representation given by the description
property defined in the CustomStringConvertible
protocol?
The motivation is I want to create shallow wrappers around Strings, so I can semantically type-check my code. For example instead of writing func login (u : String, p : String) -> Bool
I would instead write func login (u : UserName, p : Password) -> Bool
where the (failable) initialisers for UserName
and Password
do validation. For example I might write
struct UserName : TypedString {
let description : String
init?(userName : String) {
if userName.isEmpty { return nil; }
self.description = userName
}
}
What you want is totally possible, the error message you're receiving just isn't making it very clear what the problem is: your syntax for a computed property is incorrect. Computed properties need to be explicitly typed and don't use an equals sign:
extension TypedString {
var hashValue: Int { return self.description.hashValue }
}
This works fine!