Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"static let" vs "let" for declaring class specific constants

class CurrencyConverter {

    // 1
    private let conversionRate = 1.3 

    // 2
    private static let conversionRate = 1.3

    func convertToForeign(fromlocal local: Double) -> Double {
        return local * CurrencyConverter.conversionRate
    }
}

let c = CurrencyConverter()
print(c.convertToForeign(fromlocal: 5))

With reference to the code snippet above, assume that I need to use the constant conversionRate ONLY in an instance method.

What are the pros & cons of declaring conversionRate as only (1)let vs (2)static let ?

Which style would be more readable & optimised?

Additionally, let's say I will only need 1 short lived instance of CurrencyConverter and conversionRate itself is bulky (an array of 10K Doubles). Will (1)let conversionRate be more memory optimised?

like image 994
Raunak Avatar asked Dec 14 '25 15:12

Raunak


1 Answers

Neither. Use an uninhabited (caseless) enum to create a Constant namespace; it reads better.

class CurrencyConverter {
    private enum Constant {
        static let conversionRate = 1.3
    }
    func convertToForeign(fromlocal local: Double) -> Double {
        return local * Constant.conversionRate
    }
}

let c = CurrencyConverter()
print(c.convertToForeign(fromlocal: 5))
like image 79
Josh Homann Avatar answered Dec 18 '25 00:12

Josh Homann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!