Why doesn't Swift allow setting value of an optional constant after object initialization?

前端 未结 2 1662
旧巷少年郎
旧巷少年郎 2021-01-29 06:51

The code below creates a compile error saying \"error: return from initializer without initializing all stored properties (\'self.response\' not initialized)\"

c         


        
相关标签:
2条回答
  • 2021-01-29 07:35

    Because Swift tries to make you implement safe code, and having uninitialized stored properties is really not safe, because you or a client of your class may use that constant before it is properly set and the result will be undefined. This is a cause of a lot of bugs that may not be immediately caught.

    Moreover, because an optional constant stored property is initialized as having a nil value, if you were able to change its value after initialization you would violate the "constantness" of your constant. That is why you need to declare it as a var.

    0 讨论(0)
  • 2021-01-29 07:42

    Optional variables / properties are automatically set to nil by definition if no initial value is provided in the declaration line.

    An optional constant is stuck to nil which makes no sense...

    Therefore the compiler doesn't let you declare an optional constant this way.

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