When programming in Swift, what are the advantages and disadvantages for using a struct to hold all your Constants?
Normally, I would go for a class, but swift classes don't support stored type properties yet. I'd like to write my code in the form of Sample A rather in Sample B, purely because of readability, less lines of code and the single statement does what is read (a readable constant that can't be over-written).
// Sample A.swift
struct Constant {
static let PI = 3.14
}
//Sample B.swift
private let globalPI = 3.14
class Constant {
class var PI: Float {
return globalPI
}
}
If I am just referencing Constant.PI from a Struct perspective (for use in computations, printing, conditionals or whatever), am I being wasteful with the copies that are being made? Are there copies made, if I am just referencing the constant as Constant.PI in other parts of my code?
You can declare a class constant in Swift:
class Foo {
class var PI : Double { return 3.1416 }
}
The key is to define the custom getter and no setter.
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