Swift 访问协议扩展中协议的计算属性
假设我有这样的协议Swift 访问协议扩展中协议的计算属性,swift,swift-extensions,swift-protocols,Swift,Swift Extensions,Swift Protocols,假设我有这样的协议 protocol TypedString : CustomStringConvertible, Equatable, Hashable { } func == <S : TypedString, T : TypedString> (lhs : T, rhs : S) -> Bool { return lhs.description == rhs.description } 但问题是,我使用未解析标识符self时出现了一个错误 如何使用custom
protocol TypedString : CustomStringConvertible, Equatable, Hashable { }
func == <S : TypedString, T : TypedString> (lhs : T, rhs : S) -> Bool {
return lhs.description == rhs.description
}
但问题是,我使用未解析标识符self时出现了一个错误
如何使用customStringConverable
协议中定义的description
属性给出的字符串表示创建Hashable
的默认实现
其动机是我想在字符串周围创建浅包装,这样我就可以对代码进行语义类型检查。例如,我不写func登录(u:String,p:String)->Bool
而是写func登录(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 }
}
这个很好用
extension TypedString {
var hashValue: Int { return self.description.hashValue }
}