Lazy Var vs Let

SwiftVarLazy InitializationLet

Swift Problem Overview


I want to use Lazy initialization for some of my properties in Swift. My current code looks like this:

lazy var fontSize : CGFloat = {
  if (someCase) {
    return CGFloat(30)
  } else {
    return CGFloat(17)
  }
}()

The thing is that once the fontSize is set it will NEVER change. So I wanted to do something like this:

lazy let fontSize : CGFloat = {
  if (someCase) {
    return CGFloat(30)
  } else {
    return CGFloat(17)
  }
}()

Which is impossible.

Only this works:

let fontSize : CGFloat = {
  if (someCase) {
    return CGFloat(30)
  } else {
    return CGFloat(17)
  }
}()

So - I want a property that will be lazy loaded but will never change. What is the correct way to do that? using let and forget about the lazy init? Or should I use lazy var and forget about the constant nature of the property?

Swift Solutions


Solution 1 - Swift

This is the latest scripture from the Xcode 6.3 Beta / Swift 1.2 release notes:

> let constants have been generalized to no longer require immediate > initialization. The new rule is that a let constant must be > initialized before use (like a var), and that it may only be > initialized: not reassigned or mutated after initialization. > > This enables patterns like:

let x: SomeThing
if condition {
	x = foo()
} else {
	x = bar()
}

use(x)

> which formerly required the use of a var, even though there is no > mutation taking place. (16181314)

Evidently you were not the only person frustrated by this.

Solution 2 - Swift

Swift book has the following note:

> You must always declare a lazy property as a variable (with the var keyword), because its initial value might not be retrieved until after instance initialization completes. Constant properties must always have a value before initialization completes, and therefore cannot be declared as lazy.

This makes sense in the context of implementing the language, because all constant stored properties are computed before initialization of an object has finished. It does not mean that the semantic of let could have been changed when it is used together with lazy, but it has not been done, so var remains the only option with lazy at this point.

As far as the two choice that you presented go, I would decide between them based on efficiency:

  • If accessing the value of a property is done rarely, and it is expensive to compute upfront, I would use var lazy
  • If the value is accessed in more than 20..30% of cases or it is relatively inexpensive to compute, I would use let

Note: I would further optimize your code to push the conditional into CGFloat initializer:

let fontSize : CGFloat = CGFloat(someCase  ? 30 : 17)

Solution 3 - Swift

As dasblinkenlight points out lazy properties should always be declared as variables in Swift. However it is possible make the property read-only so it can only be mutated from within the source file that the Entity was defined in. This is the closest I can get to defining a "lazy let".

private(set) lazy var fontSize: CGFloat = {
    if someCase {
        return 30
    } else {
        return 17
    }
}()

Solution 4 - Swift

You can use Burritos for lazy constant properties. This library provides different property wrappers for Swift 5.1. Install it with CocoaPods by adding the following line to your Podfile:

pod 'Burritos'

With this library you can replace

lazy var fontSize : CGFloat = {
  if (someCase) {
    return CGFloat(30)
  } else {
    return CGFloat(17)
  }
}()

with

@LazyConstant var fontSize : CGFloat = {
    if (someCase) {
        return CGFloat(30)
    } else {
        return CGFloat(17)
    }
}()

And then self.fontSize = 20 leads to compilation error.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYogevSittonView Question on Stackoverflow
Solution 1 - SwiftChris ConoverView Answer on Stackoverflow
Solution 2 - SwiftSergey KalinichenkoView Answer on Stackoverflow
Solution 3 - SwiftsdduursmaView Answer on Stackoverflow
Solution 4 - SwiftRoman PodymovView Answer on Stackoverflow