Problems with Swift Declaration

Tobias

I just ask myself why I can't do something like this directly under my Class Declaration in Swift:

let width = 200.0
let height = 30.0

let widthheight = width-height

I can not create a constant with 2 other constants. If I use this inside a function/method everything works fine.

Thanks

Jean-Philippe Pellet

When you write let widthheight = width - height, this implicitly means let widthheight = self.width - self.height. In Swift, you're simply not allowed to use self until all its members have been initialised — here, including widthheight.

You have a little bit more flexibility in an init method, though, where 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
    }

}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related