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
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.
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.
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.
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
}
}
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With