swift - Access Computed Property of a Protocol in a Protocol Extension -
assume have protocol like
protocol typedstring : customstringconvertible, equatable, hashable { } func == <s : typedstring, t : typedstring> (lhs : t, rhs : s) -> bool { return lhs.description == rhs.description }
i want able provide default implementation of hashable
:
extension typedstring { var hashvalue = { return self.description.hashvalue } }
but problem error use of unresolved identifier self
.
how create default implementation of hashable
using string representation given description
property defined in customstringconvertible
protocol?
the motivation want create shallow wrappers around strings, can semantically type-check code. example instead of writing func login (u : string, p : string) -> bool
instead write func login (u : username, p : password) -> bool
(failable) initialisers username
, password
validation. example might write
struct username : typedstring { let description : string init?(username : string) { if username.isempty { return nil; } self.description = username } }
what want totally possible, error message you're receiving isn't making clear problem is: syntax computed property incorrect. computed properties need explicitly typed , don't use equals sign:
extension typedstring { var hashvalue: int { return self.description.hashvalue } }
this works fine!
Comments
Post a Comment