访问协议扩展中的协议的计算属性

时间:2016-05-28 12:17:32

标签: 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
}

我希望能够提供Hashable的默认实现:

extension TypedString {
    var hashValue = { return self.description.hashValue }
}

但问题是我收到错误Use of unresolved identifier self

如何使用Hashable协议中定义的description属性提供的字符串表示创建CustomStringConvertible的默认实现?

动机是我想在Strings周围创建浅包装器,所以我可以在语义上键入 - 检查我的代码。例如,我不是写func login (u : String, p : String) -> Bool而是写func login (u : UserName, p : Password) -> Bool,而UserNamePassword的(可用的)初始化程序会进行验证。例如,我可能会写

struct UserName : TypedString {
    let description : String

    init?(userName : String) {
        if userName.isEmpty { return nil; }

        self.description = userName
    }
}

1 个答案:

答案 0 :(得分:2)

你想要的是完全可能的,你收到的错误信息并不是很清楚问题是什么:你的计算属性的语法是不正确的。计算属性需要显式输入,不要使用等号:

extension TypedString {
    var hashValue: Int { return self.description.hashValue }
}

这很好用!

相关问题