如何扩展多个类的Swift [英] How to make extension for multiple classes Swift

查看:96
本文介绍了如何扩展多个类的Swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个扩展名:

extension UILabel {
    func animateHidden(flag: Bool) {
        self.hidden = flag
    }
}

我需要为UIImageView做相同的事情,但是我不想复制整个代码.可以扩展多个类吗?

I need to make the same one for UIImageView but I don't want to copy that whole code. Is it possible to make an extension for multiple classes?

谢谢.

推荐答案

您可以制定协议并对其进行扩展.

You could make a protocol and extend it.

类似的东西:

protocol Animations {
    func animateHidden(flag: Bool)
}

extension Animations {
    func animateHidden(flag: Bool) {
        // some code
    }
}

extension UILabel: Animations {}

extension UIImageView: Animations {}

您的方法将可用于扩展类:

Your method will be available for the extended classes:

let l = UILabel()
l.animateHidden(false)

let i = UIImageView()
i.animateHidden(false)

在注释中,您问:在这种情况下,如何在animateHidden函数中为UILabelUIImageView调用self?".您可以通过限制扩展名来做到这一点.

In a comment, you've asked: "in this case how to call self for UILabel and UIImageView in animateHidden function?". You do that by constraining the extension.

带有where子句的示例:

extension Animations where Self: UIView {
    func animateHidden(flag: Bool) {
        self.hidden = flag
    }
}

感谢@ Knight0fDragon对where子句的出色评论.

Thanks to @Knight0fDragon for his excellent comment about the where clause.

这篇关于如何扩展多个类的Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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