使用Self作为通用参数 [英] Using Self as generic parameter

查看:66
本文介绍了使用Self作为通用参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的通用类:

I have simple generic class:

class MyClass<T> {
    let closure: (T -> Void)

    init(closure: T -> Void) {
        self.closure = closure
    }
}

我想编写 UIView 的扩展名,该扩展名将对 UIView 的任何子类应用闭包:

I would like to write an extension for UIView which would apply closure to any subclass of UIView:

extension UIView {
    func apply(c: MyClass<Self>) -> Self {
        c.closure(self)
        return self
    }
}

但这给我一个错误:'Self'仅在协议中可用,或者作为类中方法的结果可用.

But it gives me an error: 'Self' is only available in a protocol or as the result of a method in a class.

是否有解决此代码的解决方案?

Is there any solution to fix this code?

推荐答案

您可以通过创建UIView以及所有子类依次采用的协议来实现此目的:

You can achieve this by creating a protocol that UIView and in turn all subclasses will adopt:

protocol View {}
extension UIView:View {}

extension View  {
    func apply(c:MyClass<Self>) -> Self {
        c.closure(self)
        return self
    }
}

let m = MyClass<UILabel>(closure: {t in})
let l = UILabel().apply(m) // UILabel returned

这篇关于使用Self作为通用参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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