LoginSignup
0
1

More than 3 years have passed since last update.

Initialization Closureとglobal定数を組み合わせて、computedライクなglobal定数を作る

Posted at

Initialization Closureとは?

Initialization closureは、以下の特徴を持ちます

  • closure内でpropertyに操作を加えられる
  • stored propertyである(値が割り当てられるタイミングはclassからinstanceが生成された時)

If a stored property’s default value requires some customization or setup, you can >use a closure or global function to provide a customized default value for that >property. Whenever a new instance of the type that the property belongs to is >initialized, the closure or function is called, and its return value is assigned >as the property’s default value.

公式ドキュメント

主にUIをコードで記述する際に用いられます。
参考記事

Globalな定数(変数)の特徴

Globalな定数(変数)は以下の特徴を持つ

  • lazyである(割り当てられるタイミングは値が呼ばれた時)

Global constants and variables are always computed lazily, in a similar manner to >Lazy Stored Properties. Unlike lazy stored properties, global constants and >variables don’t need to be marked with the lazy modifier.
Local constants and variables are never computed lazily.

それぞれの特徴を組み合わせると、computedライクなglobal定数を作ることができます。

ViewController.swift
let somePattern: FetchedValue = {
   let defalutValue = "hoge"
   return isFetchedCompleted ? fetchedValue : defaultValue
}()

これは、外部サービスを使って、複数画面でABテストを行いたい/アプリの挙動を変えたい場合に以下の性質を持つので便利です。

  • lazyなので、アプリ起動後にfetchが間に合わない場合でも、対象画面に遷移するまで時間を稼げる(=テストパターンに割り振られるユーザー数を増やせる)
  • globalなので、各画面でfetchを行わなくて良い
  • 各画面でfetchを行わないので、画面毎に挙動が異なることがない
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1