Quick Declaration Issues

I just ask myself why I can't do something like this right under my class declaration in Swift:

let width = 200.0 let height = 30.0 let widthheight = width-height 

I cannot create a constant with two other constants. If I use this inside a function / method, everything works fine.

thanks

+6
source share
3 answers

When you write let widthheight = width - height , this implicitly means let widthheight = self.width - self.height . In Swift, you are simply not allowed to use self until all of its members are initialized - here, including widthheight .

You have a bit more flexibility in the init method, although you can write things like this:

 class Rect { let width = 200.0 let height = 30.0 let widthheight: Double let widthheightInverse: Double init() { // widthheightInverse = 1.0 / widthheight // widthheight not usable yet widthheight = width - height widthheightInverse = 1.0 / widthheight // works } } 
+11
source

This is a candidate for a computed property as such:

 class Foo { let width = 200.0 let height = 30.0 var widthheight : Double { return width - height } } 

You can ask the question "but it is calculated every time"; perhaps your application will depend on one subtraction done repeatedly, but it is unlikely. If subtraction is a problem, set widthheight to init()

+1
source

For such things, you can use class variables. The code will look like this:

 class var width = 200.0 class var height = 30.0 class var widthheight = width - height 

But when you try, you will see a compiler error:

Class variables are not yet supported

I assume that they have not yet implemented this feature. But at the moment there is a solution. Just move your declarations outside the class declaration, for example:

 let width = 200.0 let height = 30.0 let widthheight = width - height class YourClass { ... 
-2
source

Source: https://habr.com/ru/post/970622/


All Articles