kodeco.com Forums

Video Tutorial: iOS App Extensions Part 7: Today Extensions: Core Data

In this video tutorial you'll learn how to share data files between the app and the extension by sharing a single core data store.


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/2076-video-tutorial-ios-app-extensions-part-7-today-extensions-core-data

Sorry, but I get stuck with the syntax here in TodayViewController.swift.

I followed all the swift 2 video tutorial series, but can not remember how this construct works in detail:

lazy var dateFormatter: NSDateFormatter = { let dateFmt = NSDateFormatter() dateFmt.dateStyle = .MediumStyle dateFmt.timeStyle = .ShortStyle return dateFmt }()
  1. what does lazy mean?
  2. is dateFormatter a calculated/computed property?
  3. I have no clue what the equal sign before the curly bracket means
  4. I have no clue how to interpret the ending …}()

Any advice is really appreciated.
Thanks,
Gerd

Hi @gerdmuller.de, just a note that this series has been updated to Swift 2. You can find the updated video here: https://www.raywenderlich.com/127469/video-tutorial-ios-app-extensions-part-7-today-extensions-core-data-2

To answer your questions:

  1. lazy means this property won’t be initialized—that is, the attached closure won’t be run—until the property is first accessed. Rather than happening when the containing object is initialized as with most properties, this one will be initialized “on demand”.

  2. It’s technically a regular property that happens to be lazy. It should probably be declared with let instead of var too!

  3. and 4. Because the property is lazy, you don’t assign a value to it like var myString = "hello". Instead, you assign a closure that when run, will return the initial value that you want. But because closures are types, you’d get a mismatch: a closure that returns String is different from a String itself. Thus you need the () at the end to “call” the closure and access its return value.

I hope that helps and makes sense. Thanks for your question and for subscribing to the videos!