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

Class has no initializers

Antonio Bello
Apr 22, 2015
<p>In swift all non-optional stored properties must be initialized, either inline or in an initializer.</p> <p>In your class there are 6 optional properties (all defined as implicitly unwrapped, the ones ending by <code>!</code>) and 3 non optional properties (<code>currentPlayerMove</code>, <code>player1Score</code> and <code>player2Score</code>). You should either initialize them inline:</p> <pre><code>var currentPlayerMove: Int = 0 var player1Score: Int = 0 var player2Score: Int = 0 </code></pre> <p>or in an initializer, or make them optional, or make them implicitly unwrapped optionals:</p> <pre><code>var currentPlayerMove: Int! var player1Score: Int! var player2Score: Int! </code></pre> <p>and initialize <strong>before using them</strong> - a good place is <code>viewDidLoad</code>:</p> <pre><code>func viewDidLoad() { super.viewDidLoad() currentPlayerMove = 0 player1Score = 0 player2Score = 0 ... } </code></pre> <p>Some guidelines:</p> <ul> <li>use a normal optional if the property can be nil</li> <li>use implicitly unwrapped optional if the property is supposed to be not nil, but you can't initialize inline or in an initializer - <strong>warning</strong>: accessing implicitly unwrapped when it's nil causes a runtime exception, always be sure to initialize properly before use</li> <li>use non optional if the property is supposed to be not nil, and you can initialize either inline or in an initializer - <strong>this should always be the preferred solution instead of implicitly unwrapped, when possible</strong></li> </ul> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/29682395/Class%20has%20no%20initializers/29682564">Stack Overflow</a>.</p>
comments powered by Disqus