所选类实例的Swift扩展

时间:2016-06-07 14:41:43

标签: swift swift2 categories swift-extensions

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

似乎所有Swift扩展都是在没有导入的情况下自动引入的。你如何在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() {

  }
}

3 个答案:

答案 0 :(得分:8)

定义一个将作为选择的协议,扩展应该是否可用:

   <div ng-repeat="p in points" id="point-4" class="point point-off" role="button" tabindex="0" style="">
            <div class="point-number ng-binding">4</div>
            <div class="point-state-configure pump-state-off" style=""></div>           
            <div class="point-amount ng-binding">926.93</div>
            <div class="point-quantity ng-binding">417.35 L</div>
        </div>

然后定义协议的扩展名,但仅适用于protocol UIViewExtensions { } 的子类(反之亦然)

UIView

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

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

如果没有定义协议,它也没有扩展名:

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

<强>更新

protocol extensions don't do class polymorphism开始,如果你需要覆盖函数,我唯一能想到的就是子类:

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

这也可以与扩展相结合,但我不认为它仍然有用了。

答案 1 :(得分:3)

您可以通过在扩展名之前添加私有来为特定类创建私有扩展名,如此

private extension UIView {

  func extraCapability() {

  }
}

这意味着它只能用于该特定类。但是您需要将此添加到需要此扩展的每个类。据我所知,无法像在Obj-c中那样导入扩展名

答案 2 :(得分:0)

  

请注意   Swift中的私有访问与大多数其他语言中的私有访问不同,因为它的范围是封闭的源文件而不是封闭的声明。这意味着类型可以访问在与自身相同的源文件中定义的任何私有实体,但如果扩展在单独的源文件中定义,则扩展无法访问该类型的私有成员。

根据Apple here的说法,您似乎无法在单独的文件中将扩展名设为私有。

您可以在同一源文件中创建私人扩展程序。