Swift call class function from corresponding subclass in superclass function

前端 未结 3 2209
迷失自我
迷失自我 2020-12-15 11:58

I would like to implement init(coder aDecoder: NSCoder!) in a superclass, and use it in all subclasses by calling a class method on the particular subclass in t

相关标签:
3条回答
  • 2020-12-15 12:07

    I think I caught what you mean. You create a Base class, implementing an initializer and a class (static) function:

    class Base {
        class func dummyDict() -> Dictionary<String, String> {
            return ["base1": "val1"]
        }
    
        init() {
            for (key, value) in self.dynamicType.dummyDict() {
                println("encoding \(value) for key \(key)")
            }
        }
    }
    

    Next you want to create subclasses, and have the initializer to call an overridden version of the dummyDict method. You simply have to override that method:

    class Subclass1 : Base {
        override class func dummyDict() -> Dictionary<String, String> {
            return ["subclass1": "sub1"]
        }
    }
    

    Now, when you create an instance of Subclass1, what's printed is:

    encoding sub1 for key subclass1
    

    which is the expected output.

    Note the for loop in the initializer is using self.dynamicType.dummyDict() rather than Base.dummyDict(). The latter always calls the class method defined in the Base class, whereas the former calls it in the scope of the actual class inherited from Base

    0 讨论(0)
  • 2020-12-15 12:11

    [DELETED]

    use dynamicType as Antonio suggested in his answer

    class Test : NSObject {
        class func dummy() -> String { 
            return "t"
        }
    
        init() {
            super.init()
            println("\(self.dynamicType.dummy())")
        }
    }
    
    class Test1 : Test {
        override class func dummy() -> String  {
            return "t1"
        }
    }
    
    class Test2 : Test {
        override class func dummy() -> String  {
            return "t2"
        }
    }
    
    0 讨论(0)
  • 2020-12-15 12:30

    dynamicType is deprecated in Swift 3. We must use type(of:).

    So Antonio's example is now:

    class Base {
        class func dummyDict() -> [String: String] {
            return ["base1": "val1"]
        }
    
        init() {
            for (key, value) in type(of: self).dummyDict() {
                print("encoding \(value) for key \(key)")
            }
        }
    }
    
    class Subclass1 : Base {
        override class func dummyDict() -> [String: String] {
            return ["subclass1": "sub1"]
        }
    }
    
    0 讨论(0)
提交回复
热议问题