选定类实例的Swift扩展 [英] Swift extension for selected class instance

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

问题描述

在Objective-C类别中,可以通过将类别的标题包含在类中来引入类别方法引入的扩展功能.

In Objective-C category, you can bring in the extended capability introduced by the category methods by including the header of the category in your class.

似乎所有Swift扩展都自动引入而无需导入.您如何在Swift中实现同一目标?

It seems like all Swift extensions are automatically introduced without import. How do you achieve the same thing in Swift?

例如:

extension UIView {
  // only want certain UIView to have this, not all
  // similar to Objective-C, where imported category header
  // will grant the capability to the class
  func extraCapability() {

  }
}

推荐答案

定义扩展协议,无论扩展名是否可用:

Define a protocol that will serve as a selection, wether the extensions should be available or not:

protocol UIViewExtensions { }

然后定义协议的扩展名,但仅针对 UIView 的子类(反之亦然):

then define an extension for the protocol, but only for subclasses of UIView (the other way around won't work):

extension UIViewExtensions where Self: UIView {
    func testFunc() -> String { return String(tag) }
}

定义为具有协议的类也将具有扩展名:

A class that is defined to have the protocol will also have the extension:

class A: UIView, UIViewExtensions { }    
A().testFunc() //has the extension

如果未定义为具有协议,则也将不具有扩展名:

And if it is not defined to have the protocol, it will also not have the extension:

class B: UIView {}    
B().testFunc() //execution failed: MyPlayground.playground:17:1: error: value of type 'B' has no member 'testFunc'

更新

由于协议扩展不执行类多态性,如果您需要覆盖函数,那么我唯一想到的就是of是子类:

Since protocol extensions don't do class polymorphism, if you need to override functions, the only thing I can think of is to subclass:

class UIViewWithExtensions: UIView {
    override func canBecomeFocused() -> Bool { return true }
}
UIViewWithExtensions().canBecomeFocused() // returns true

这也可以与扩展名结合使用,但我认为它仍然没有任何意义.

this could also be combined with the extension, but I don't think it would still make much sense anymore.

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

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