× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Swift call class function from corresponding subclass in superclass function

Antonio Bello
Mar 01, 2015
<p>I think I caught what you mean. You create a <code>Base</code> class, implementing an initializer and a class (static) function:</p> <pre><code>class Base { class func dummyDict() -&gt; Dictionary&lt;String, String&gt; { return ["base1": "val1"] } init() { for (key, value) in self.dynamicType.dummyDict() { println("encoding \(value) for key \(key)") } } } </code></pre> <p>Next you want to create subclasses, and have the initializer to call an overridden version of the <code>dummyDict</code> method. You simply have to override that method:</p> <pre><code>class Subclass1 : Base { override class func dummyDict() -&gt; Dictionary&lt;String, String&gt; { return ["subclass1": "sub1"] } } </code></pre> <p>Now, when you create an instance of <code>Subclass1</code>, what's printed is:</p> <pre><code>encoding sub1 for key subclass1 </code></pre> <p>which is the expected output.</p> <p>Note the <code>for</code> loop in the initializer is using <code>self.dynamicType.dummyDict()</code> rather than <code>Base.dummyDict()</code>. The latter always calls the class method defined in the <code>Base</code> class, whereas the former calls it in the scope of the actual class inherited from <code>Base</code></p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/24711515/Swift%20call%20class%20function%20from%20corresponding%20subclass%20in%20superclass%20function/24711715">Stack Overflow</a>.</p>
comments powered by Disqus