Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Lazy stored property

Lazy stored property

関モバ#4の発表資料です.
Lazy stored propertyについて話しました.

yashigani

July 27, 2015
Tweet

More Decks by yashigani

Other Decks in Programming

Transcript

  1. • Swift has two types of properties • computed or

    stored • Indicate lazy stored property by lazy modifier • Lazy stored property created when it is first accessed
  2. class Lazy { lazy var person: String = { println("lazy

    evaluation!") return "someone" }() } let l = Lazy() let person = l.person // => lazy evaluation! println(person) // => someone
  3. class JSONDecoder { private var data: NSData private(set) lazy var

    JSONObject: [String: AnyObject] = { let data = self.data let JSONObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(dat a, options: .AllowFragments, error: nil) return JSONObject as? [String: AnyObject] ?? [:] }() init(data: NSData) { self.data = data } }
  4. // ͜ΕΑΓ final class ViewController:
 UIViewController { var user: User!

    var client: APIClient! var userManager: UserManager! { didSet { user = userManager.loginUser client = APIClient(user.session) } } }
  5. // ͬͪ͜ͷ΄͏͕͍͍ΑͶ final class ViewController:
 UIViewController { lazy var user:

    User = self.userManager.loginUser lazy var client: APIClient = APIClient(self.user.session) var userManager: UserManager! }
  6. import MBProgressHUD // MBProgressHUDͱ͔͸͜͏͓ͯ͘͠ͱศར final class ViewController: UIViewController { lazy

    var : MBProgressHUD = { var HUD = MBProgressHUD(view: self.view) self.view.addSubview(HUD) return HUD }() }
  7. class Lazy { var person: String = "someone" lazy var

    greeting: String = "Hello, lazy \(self.person)!" } let l = Lazy() l.person = "programmer" let person = l.person println(person) // => programmer println(l.greeting) // => Hello, lazy programmer
  8. // Application Context public class Context { public static let

    staticContext = Context() public var path: String { return "data.txt" } } // A View Controller final public class ViewController: UIViewController { public var context = Context.staticContext lazy public var dataStore: String = self.context.path }
  9. // test code func testViewController() { class MockContext: Context {

    override var path: String
 { return "test.txt" } } let vc = ViewController() // ॳظԽ͞ΕΔ·͑ʹcontextΛࠩ͠ସ͑Δ vc.context = MockContext() assert(vc.dataStore == "test.txt") }