swift - 在协议(protocol)扩展中访问协议(protocol)的计算属性

标签 swift swift-extensions swift-protocols

假设我有一个类似的协议(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 UserNamePassword 的(失败的)初始化程序在其中进行验证。例如我可能会写

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/

相关文章:

arrays - 在数组中存储值与在 Swift 中创建扩展函数

swift - 在 Swift 中,协议(protocol)扩展是否允许函数体?

ios - 检测应用程序何时最小化(iOS)

ios - performseguewithidentifier 延迟工作

ios - 从 Assets 中选择它未显示在 SWIFT 的选项卡栏 Controller 中的图像

objective-c - Objective-C 类别中的 Swift 协议(protocol)

ios - 如何在 iOS 10 中替换折旧的 UILocalNotification 并添加 UNNotificationAction

ios - 通用 IBDesginables UIView 扩展

c - 获取协议(protocol)中方法 block 的 NSMethodSignature