Why do I get a “Variable used before being initialized” error on the line that I initialise the variable in Swift?

后端 未结 1 1781
轻奢々
轻奢々 2020-12-05 01:46

I\'m struggling to understand why I\'m getting this compiler error in an iOS project using Swift. If I create the following class:

class InitTest {

    let          


        
相关标签:
1条回答
  • 2020-12-05 02:42

    Swift has this behaviour because of two phase initialisation. From Apple's Swift book:

    Class initialization in Swift is a two-phase process. In the first phase, each stored property is assigned an initial value by the class that introduced it. Once the initial state for every stored property has been determined, the second phase begins, and each class is given the opportunity to customize its stored properties further before the new instance is considered ready for use.

    Classes need some kind of default value before the first phase ends. Customising values is part of the second phase.

    Objective-C didn't have this behaviour because it could always give 0 as default for primitives and nil for objects, but in Swift there is no mechanism to give such a default value.

    0 讨论(0)
提交回复
热议问题