Declare array of classes that conform to a protocol

后端 未结 4 1624
不知归路
不知归路 2020-12-19 04:40

Lets say I have created this protocol and a couple of classes

import UIKit

protocol ControllerConstructorProtocol {
    class func construct() -> UIViewC         


        
4条回答
  •  醉梦人生
    2020-12-19 05:25

    Try this:

    var myConst = MyConstructor()
    var myOthConst = MyOtherConstructor()
    
    var array:[AnyObject] = [
        myConst,
        myOthConst
    ]
    
    for a in array
    {
        if a is MyConstructor
        {
            println("a is type of MyConstructor")
            (a as! MyConstructor).myMethod()
        }
        else if a is MyOtherConstructor
        {
            println("a is type of MyOtherConstructor")
            (a as! MyOtherConstructor).myMethod()
        }
    }
    

    Another solution, although not that pretty...

提交回复
热议问题