Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with Swift Declaration

Tags:

xcode

ios

swift

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

like image 778
Tobias Avatar asked Jun 10 '14 12:06

Tobias


People also ask

What is declaration in Swift?

A declaration introduces a new name or construct into your program. For example, you use declarations to introduce functions and methods, to introduce variables and constants, and to define enumeration, structure, class, and protocol types.

What is error handling in Swift?

Error handling is the process of responding to and recovering from error conditions in your program. Swift provides first-class support for throwing, catching, propagating, and manipulating recoverable errors at runtime. Some operations aren't guaranteed to always complete execution or produce a useful output.

Is Swift a good programming language?

Swift is a powerful and intuitive programming language for iOS, iPadOS, macOS, tvOS, and watchOS. Writing Swift code is interactive and fun, the syntax is concise yet expressive, and Swift includes modern features developers love. Swift code is safe by design and produces software that runs lightning-fast.


2 Answers

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
    }

}
like image 185
Jean-Philippe Pellet Avatar answered Sep 21 '22 12:09

Jean-Philippe Pellet


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 might raise an issue of 'but it is computed each time'; perhaps your application will depend on a single subtraction done repeatedly - but not likely. If the subtraction is an issue, set widthheight in init()

like image 42
GoZoner Avatar answered Sep 21 '22 12:09

GoZoner