我可以在Swift中模拟特征/混合吗? [英] Can I simulate traits/mixins in Swift?

查看:63
本文介绍了我可以在Swift中模拟特征/混合吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

斯威夫特有没有一种混合性格的方式,如斯卡拉? Swift书中有关使用扩展将协议添加到现有类的部分非常接近.但是,由于协议不能包含实现,因此不能用于将代码混合到类中.还有另一种方法吗?

Does Swift have a way of mixing in traits, a la Scala? The section of the Swift book on using extensions to add protocols to existing classes comes tantalizingly close. However, since protocols can't contain an implementation, this can't be used to mix code into a class. Is there another way?

推荐答案

从Swift 2.0开始,是的!

As of Swift 2.0, yes!

提供默认实现

您可以使用协议扩展来提供默认实现 该协议的任何方法或属性要求.如果一个 符合类型提供了自己的所需方法的实现 或属性,则将使用该实现代替 由扩展程序提供.

You can use protocol extensions to provide a default implementation to any method or property requirement of that protocol. If a conforming type provides its own implementation of a required method or property, that implementation will be used instead of the one provided by the extension.

这篇关于我可以在Swift中模拟特征/混合吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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