【问题标题】:How to make an array of objects that confirm a certain protocol and have a different parent class?如何制作一个确认某个协议并具有不同父类的对象数组?
【发布时间】:2015-09-14 02:03:55
【问题描述】:

我有一个设计相关的问题。

有一个继承自 CAShapeLayer 的类和一个继承自 CATextLayer 的类,并且它们都确认了某个协议,如下所示。

protocol HogeProtocol {
    func aFunction()
}

class A: CAShapeLayer, HogeProtocol {
    func aFunction() {
        print("I am Class A")
    }
}

class B: CATextLayer, HogeProtocol {
    func aFunction() {
        print("I am Class B")
    }
}

UIView 的一个子类有一个确认此协议的对象数组:

class CustomView: UIView {
    var customLayers = [HogeProtocol]()
    func callTheFunctionAndAddSublayer() {
        // some implementation
    }
}

我在这里尝试做的是调用 customLayers 的 aFunction() 并将它们添加到此自定义 UIView 的层中。

class CustomView: UIView {

    var customLayers = [HogeProtocol]()

    func callTheFunctionAndAddSublayer() {

        for customLayer in customLayers {
            customLayer.aFunction() // can call
            layer.addSublayer(customLayer) // cannot call.. 
        }

    }
}

在这种情况下,元素正在确认协议但不能添加到子层,因为它们不是从 CALayer 继承的。我希望我可以创建一个从 CALayer 继承的对象数组(这是 CAShapeLayer 和 CATextLayer 的公共父类)并确认协议但 swift 不允许我这样做(据我所知......)

这似乎是一个非常简单的问题,并且猜测可能已经有了解决方案,但经过数小时的谷歌研究后我找不到任何答案...... 有什么想法吗?

【问题讨论】:

  • 我认为目前在 Swift 中不可能声明一个属于一个类的变量同时符合一个协议。我已经向 Apple 提交了一个错误报告,它被标记为另一个当前打开的错误的副本。对于您的情况,我建议存储在两个单独的变量中,一个用于类,一个用于协议。
  • 哦,非常感谢!我会采取另一种方式,希望苹果能尽快修复这个功能......

标签: ios swift


【解决方案1】:

您需要将带有as?as! 的数组对象向下转换为CALayer。

【讨论】:

  • 谢谢...使用 if let 向下转换似乎是最直接的方法
【解决方案2】:

试试这个:

for customLayer in customLayers {
    customLayer.aFunction()
    layer.addSublayer(customLayer as! CALayer) // would crash if customLayer is not of CALayer
}

【讨论】:

    【解决方案3】:

    您可以将对象投射到 CALayer 并检查它是否真的是一种 CALayer。

    class CustomView: UIView
    {
        var customLayers = [CALayer]()
    
        func callTheFunctionAndAddSublayer()
        {
            for customLayer in customLayers
            {
                customLayer.aFunction() // can call
    
                if let layer = customLayer as? CALayer where layer.isKindOfClass(CALayer)
                {
                    layer.addSublayer(layer) 
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-22
      • 2023-01-31
      • 2020-04-21
      • 2021-08-14
      • 2020-11-14
      相关资源
      最近更新 更多