Swift:符合特定类并同时符合多个协议的属性 [英] Swift: Property conforming to a specific class and in the same time to multiple protocols

查看:85
本文介绍了Swift:符合特定类并同时符合多个协议的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Objective-C 中,可以这样写:

In Objective-C, it's possible to write something like that:

@property(retain) UIView<Protocol1, Protocol2, ...> *myView;

但是我如何快速编写这段代码?

But how can I write this code in swift?

我已经知道如何使一个属性符合许多协议,但它不能通过使用继承来工作:

I already know how to make a property conform to many protocols, but it does not work by using the inheritance:

var myView: ??? protocol<Protocol1, Protocol2, ...>

我使用了很多 UIView 子类型,比如 UIImageViewUILabel 或其他,我需要使用一些 UIViewcode> properties 加上协议中定义的一些方法.在最坏的情况下,我可以使用所需的属性创建一个 UIViewProtocol,但我想知道是否可以在 Swift 中声明具有类型和一些协议的属性/变量.

I use many UIView subtypes like UIImageView, UILabel or others, and I need to use some of the UIView properties plus some methods defined in the protocols. In the worst case I could create a UIViewProtocol with the needed properties, but I would know if it is possible in Swift to declare a property/variable with a type and some protocol to conform with.

推荐答案

您可以使用 where 子句:

where 子句使您能够要求关联类型符合到某个协议,和/或某些类型参数和关联类型相同.

A where clause enables you to require that an associated type conforms to a certain protocol, and/or that certain type parameters and associated types be the same.

要使用它,请使用 输入约束以检查类型参数与您想要的基类匹配和协议.

To use it, make the class your property is defined in a generic class with a type constraint to check if the type parameter for your property matches your desired base class and protocols.

对于您的具体示例,它可能如下所示:

For your specific example, it could look something like this:

class MyViewController<T where T: UIView, T: Protocol1, T: Protocol2>: UIViewController {
    var myView: T

    // ...
}

这篇关于Swift:符合特定类并同时符合多个协议的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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