Type Properties are Lazily Evaluated in Swift

At this time, only structs are permitted static properties (see …).  Consider the following struct with a static type property typeProperty

struct SomeStruct {
  static var typeProperty: Int {
    println("initializing typeVariable")
    return 100
  }
}

From the following invocations, we can see that the type property’s setter block is evaluated on demand:

println("typeProperty is: ")
println(SomeStruct.typeProperty)

We get the following console output:

typeProperty is: 
initializing typeVariable
100

Going back to the struct’s definition, lets add a @lazy attribute to the type property.

struct SomeStruct {
  @lazy static var typeProperty: Int {
    println("initializing typeVariable")
    return 100
  }
}

The REPL spits out an error informing us that type properties are already lazily evaluated.

Playground execution failed: error: <REPL>:4:3: error: 'lazy' attribute may not be used on a computed property
  @lazy static var typeProperty: Int {
  ^~~~~

One downside to using a setter is that the setter block is evaluated every time the type property is accessed. So for:

println("typeProperty is: ")
println(SomeStruct.typeProperty)
println(SomeStruct.typeProperty)
println(SomeStruct.typeProperty)

We get the following console output:

typeProperty is: 
initializing typeVariable
100
initializing typeVariable
100
initializing typeVariable
100

To avoid repeated evaluation, we can forego the setter block and use object instantiation instead:

var uuid: Int = 0 

class X {
  var id: Int = ++uuid
  
  init(){
    println("X(\(id)): init")
  }
}

struct SomeStruct {
  static var typeProperty: X  = X()
}

In this case, the type property is assigned only once, at first use. So for:

println("typeProperty is: ")
println(SomeStruct.typeProperty.id)
println(SomeStruct.typeProperty.id)
println(SomeStruct.typeProperty.id)

we see that X’s initializer is called once.

typeProperty is: 
X(1): init
1
1
1

2 thoughts on “Type Properties are Lazily Evaluated in Swift

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s