使类型的属性也符合 Swift 中的协议 [英] Make property of type and also conform to protocol in Swift

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

问题描述

我想创建一个特定类型且符合协议的属性,我会在 Objective-C 中这样做:

@property (nonatomic) UIViewController*控制器;

我要找的是指定属性可以设置为 UIViewController 类型的对象,该对象也符合 CustomProtocol,以便清楚基类是什么.我知道我可能只使用一个简短的类存根来获得相同的结果,即

class CustomViewController : UIViewController, CustomProtocol {}

但这似乎不是最干净的方法.

解决方案

我想不出用 Swift 表达的好方法.类型的语法是:

<块引用>

类型 → 数组类型 |字典式 |功能类型|类型标识符 |元组类型|可选类型 |隐式解包可选类型 |协议组合类型|元类型

您正在寻找的是一种 protocol-combination-type 也接受基类.(Protocol-combination-typeprotocol.)但是,目前这是不可能的.

允许具有关联类型要求的协议具有指定所需基类和所需协议的类型别名,但这些还要求在编译时知道类型,因此它不太可能成为您的可行选择.

如果你真的很喜欢它,你可以用你使用的 UIViewController 的接口部分定义一个协议,使用扩展来添加一致性,然后使用 protocol<;UIViewControllerProtocol、CustomProtocol>.

protocol UIViewControllerProtocol {func isViewLoaded() ->布尔值var 标题:字符串?{ 设置}//任何其他有趣的属性/方法}扩展 UIViewController:UIViewControllerProtocol {}类我的类{var 控制器:协议}

I would like to make a property that is of a certain type and also conforms to a protocol, which I would have done in Objective-C like this:

@property (nonatomic) UIViewController<CustomProtocol> *controller;

What I am looking for is to specify that the property can be set with an object of type UIViewController that also conforms to CustomProtocol, so that it's clear what the base class is. I know I could probably just use a short class stub to get the same results, i.e.

class CustomViewController : UIViewController, CustomProtocol {}

But this doesn't seem like the cleanest way to do it.

解决方案

I can't think of a good way to express this in Swift. The syntax for a type is:

type → array-type­ | dictionary-type­ | function-type­ | type-identifier­ | tuple-type­ | optional-type­ | implicitly-unwrapped-optional-type­ | protocol-composition-type­ | metatype-type­

What you're looking for would be a kind of protocol-combination-type that also accepts a base class. (Protocol-combination-type is protocol<Proto1, Proto2, Proto3, …>.) However, this is not currently possible.

Protocols with associated type requirements are allowed to have typealiases that specify a required base class and required protocols, but these also require the types to be known at compile-time, so it's unlikely to be a viable option for you.

If you're really into it, you can define a protocol with the parts of the interface of UIViewController that you use, use an extension to add conformance, and then use protocol<UIViewControllerProtocol, CustomProtocol>.

protocol UIViewControllerProtocol {
    func isViewLoaded() -> Bool
    var title: String? { get set }
    // any other interesting property/method
}

extension UIViewController: UIViewControllerProtocol {}

class MyClass {
    var controller: protocol<UIViewControllerProtocol, CustomProtocol>
}

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

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