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

Swift: Call self method inside init

Antonio Bello
Mar 01, 2015
<p>No, it's not a defect, simply <code>self</code> cannot be referenced in an initializer until all stored properties have been initialized, and a super class initializer has been invoked (if any).</p> <p>In your case it seems legit to do the initializations in a method, and call that from the initializer, but unfortunately it doesn't work.</p> <p>Possible solutions:</p> <ul> <li>make the properties optional or implicitly unwrapped (discouraged, unless you really need them optionals)</li> <li><p>initialize the properties with fake values before calling <code>reset</code>:</p> <pre><code>init() { self.a = 0 self.b = 0 self.c = 0 self.d = 0 reset() } </code></pre> <p>or</p> <pre><code>var a = 0 var b = 0 var c = 0 var d = 0 init() { reset() } </code></pre></li> </ul> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/28001207/Swift:%20Call%20self%20method%20inside%20init/28001307">Stack Overflow</a>.</p>
comments powered by Disqus