假设我有一个类似的协议(protocol)
protocol TypedString : CustomStringConvertible, Equatable, Hashable { }
func == <S : TypedString, T : TypedString> (lhs : T, rhs : S) -> Bool {
return lhs.description == rhs.description
}
我希望能够提供 Hashable
的默认实现:
extension TypedString {
var hashValue = { return self.description.hashValue }
}
但问题是我得到一个错误Use of unresolved identifier self
。
如何使用 CustomStringConvertible
协议(protocol)中定义的 description
属性给出的字符串表示来创建 Hashable
的默认实现?
动机是我想围绕字符串创建浅层包装器,这样我就可以对我的代码进行语义类型检查。例如,我不写 func login (u : String, p : String) -> Bool
我会写 func login (u : UserName, p : Password) -> Bool
UserName
和 Password
的(失败的)初始化程序在其中进行验证。例如我可能会写
struct UserName : TypedString {
let description : String
init?(userName : String) {
if userName.isEmpty { return nil; }
self.description = userName
}
}
最佳答案
您想要的是完全可能的,您收到的错误消息并没有很清楚地说明问题所在:计算属性的语法不正确。计算属性需要显式输入并且不要使用等号:
extension TypedString {
var hashValue: Int { return self.description.hashValue }
}
这很好用!
关于swift - 在协议(protocol)扩展中访问协议(protocol)的计算属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37498879/