使用 Swift 中的关联类型检查是否符合协议 [英] Checking conforms protocol with associatedtype in Swift

查看:88
本文介绍了使用 Swift 中的关联类型检查是否符合协议的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在类似情况下,如何检查对象是否符合可表示"协议?

How can I do a check object conforms to protocol 'Representable' in a similar situation?

protocol Representable {
    associatedtype RepresentType
    var representType: RepresentType { get set }
}

class A: UIView, Representable {
    enum RepresentType: String {
        case atype = "isa"
    }
    var representType: RepresentType = .atype
}

class B: UIView, Representable {
    enum RepresentType {
        case btype(value: String?)
    }
    var representType: RepresentType = .btype(value: nil)
}

let obj = A()
if let obj = obj as? Representable {  <<<<<<<<<<<< error
    obj.representType = A.RepresentType.atype
}

错误:协议可表示"只能用作通用约束,因为它具有 Self 或关联的类型要求如果让 obj = obj as?具有代表性

Error: Protocol 'Representable' can only be used as a generic constraint because it has Self or associated type requirements if let obj = obj as? Representable

重要的是每个类都实现其表示类型的枚举,但可以检查该类是否符合协议

It is important that each class implements its enumeration of types of representation, but the class can be checked of conforms to protocol

推荐答案

我相信您的要求是不可能的,因为 RepresentType 在确认类定义它之前仍然未知.

I believe what you're asking for is not possible, because RepresentType remains unknown until a confirming class defines it.

以下是一些处理同一问题的相关 SO 问题:

Here are some related SO questions that deal with the same issue:

在 Swift 中,如何转换为具有关联类型的协议?

为什么这会造成这么多麻烦?(相关类型的协议和类型别名)

这篇关于使用 Swift 中的关联类型检查是否符合协议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆