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?
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))
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