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 }
}