قالب وردپرس درنا توس
Home / IOS Development / # 302: Lazy Properties 🐤💤 – Little Bites of Cocoa

# 302: Lazy Properties 🐤💤 – Little Bites of Cocoa



Subjects

Topics

Today we will start looking at lazy the keyword in Swift. It describes some functionality in the language for what Apple calls "just-in-time calculation" of the work.

This is great for times when we have expensive work to perform, or maybe the job is just a little ugly complex code we want to waste. Perhaps we just want to better divide bits of our code that initiates the UI elements, usage issues are many.

Today we start with Lazy Variables . Let's go diving!

Say we have a View Controller with a titleLabel . Pretty old school standard things.

We must create titleLabel save it to a property, configure some things about it and add it to the display heirarchy.

We want this work to be done after the display is loaded and not when the display regenerator is first created so we have to put it in viewDidLoad .

Additionally, we are forced to use a UILabel! force-unwrapped type on our titleLabel property to make the compiler happy. ] [Label] : UILabel !

ride FUNC viewDidLoad () {
super . viewDidLoad ()

titleLabel = UILabel ()

titleLabel . = UIFont ( Name : "Source Sans Pro" Size ~~ POS = HEADCOMP : ] 1

8.0 [19659016])
title label . text color = UIColor . brown

display . addSubview ( Title Label )
}

Let's make our titleLabel lazy and clear this rubbish up:

  class   ViewController :   UIViewController    {
    lat    var    titleLabel  :   UILabel    =    {
      19659067] label    =   UILabel [19659016]   .      =   UIFont   (  Name :    "Source Sans Pro"    ] Size .:    18 , ] 
      label    text color    =   UIColor    brown 

      return    label 
  } () 

    ride    FUNC    viewDidLoad   ()    {
      super .   viewDidLoad   () 

      view .   addSubview   (  titleLabel ) 
  } 
} 

Neat!

We I have dramatically improved our implementation of viewDidLoad . Cool.

We also have the nicely divided code that sets that label. Cool cool

Perhaps most importantly, but now we have better expressed our intentions using language keywords (and their resulting behavior), Cool, Cool, Cool.

Note: We must use var instead of la when you define lazy features like this. Our property may not (probably) have an original value to after the appearance of our display regulator was created and its display is loaded. This completely violates the rules for allows (constants).

It's all for now, in the future Bites we will look at other Latvian listings in Swift!


Source link