【问题标题】:How to check conformance to protocol with associated type in Swift?如何在 Swift 中检查与关联类型的协议的一致性?
【发布时间】:2019-03-17 12:29:57
【问题描述】:

当我想检查一个类型是否符合简单协议时,我可以使用:

if let type = ValueType.self as? Codable.Type {}

当协议有关联类型时,例如RawRepresentableRawValue,当我这样做时:

if let type = ValueType.self as? RawRepresentable.Type {}

编译器会显示如下错误:

Protocol 'RawRepresentable' 只能用作通用约束,因为它具有 Self 或关联的类型要求


那么如何检查关联类型与协议的一致性呢?

【问题讨论】:

  • 常识...在您的ValueType 中,RawValue 是什么? :)
  • 这种检查闻起来很objective-c-ish。在像 Swift 这样的强类型语言中,应该在编译时检查类型。
  • @DominikBucher 我想它可以是任何类型

标签: swift swift-protocols associated-types


【解决方案1】:

TL;DR
编译器没有足够的信息来比较类型直到关联类型被设置


当你提到简单协议时,编译器从一开始就知道它的类型。 但是,当您使用 关联类型 引用协议时,编译器在您声明它之前并不知道它的类型。

protocol ExampleProtocol {
    associatedtype SomeType
    func foo(param: SomeType)
}

此时编译器看起来像这样:

protocol ExampleProtocol {
    func foo(param: <I don't know it, so I'll wait until it's defined>)
}

当你声明一个符合协议的类时

class A: ExampleProtocol {
    typealias SomeType = String
    func foo(param: SomeType) {

    }
}

编译器开始看到它是这样的:

protocol ExampleProtocol {
    func foo(param: String)
}

并且那么它可以比较类型。

【讨论】:

  • 在 SwiftUI 中,我们如何检查 Color 是否为 View?你能告诉我如何在 Swift 中做到这一点吗?谢谢。
  • @lochiwei,A Color 是一个后期绑定标记:SwiftUI 仅在给定环境中使用它之前将其解析为具体值。
  • 好吧,我们如何检查Rectangle 是否是View
  • @lochiwei,矩形是视图内的一个形状。
  • 我的意思是Rectangle符合InsettableShapeInsettableShape继承自Shape,而Shape继承自View,那么我们如何签入Rectangle的代码is-a View?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-13
  • 1970-01-01
  • 2018-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-24
相关资源
最近更新 更多