Created
October 20, 2015 11:51
-
-
Save safx/4755d79c59ad12a3f851 to your computer and use it in GitHub Desktop.
lazy in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Foo { | |
static var x: Int = 0 | |
lazy var a: Int! = { return x++ }() | |
} | |
class Bar { | |
static var y: Int = 0 | |
lazy var b: Int? = { return y++ }() | |
} | |
let f = Foo() | |
print(f.a) | |
f.a = nil | |
print(f.a) | |
let g = Bar() | |
print(g.b) | |
g.b = nil | |
print(g.b) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
class Foo { | |
static var x: Int = 0 | |
var lazy_a: Optional<Int!> | |
var a: Int! { | |
get { // main.Foo.a.getter | |
let val: Int! | |
if self.lazy_a != nil { // bb0 | |
switch self.lazy_a {// bb1 | |
case .Some(let v): // bb2 | |
val = v // bb5 | |
case .None: // bb3, bb4 | |
fatalError("unexpectedly found nil while unwrapping an Optional value") | |
} | |
} else { // bb6 | |
let v = { return Foo.x++ }() | |
val = .Some(v) | |
let tmp: Optional<Int!> | |
switch val { | |
case .Some: // bb7 | |
tmp = .Some(.Some(val)) | |
case .None: // bb9 | |
tmp = .None | |
} | |
self.lazy_a = tmp // bb8 | |
} | |
return val // bb10 | |
} | |
set { // main.Foo.a.setter | |
switch newValue { | |
case .None: self.lazy_a = nil | |
case .Some(let v): self.lazy_a = .Some(.Some(v)) | |
} | |
} | |
} | |
} | |
let f = Foo() | |
print(f.a) | |
f.a = nil | |
print(f.a) | |
class Bar { | |
static var y: Int = 0 | |
var lazy_b: Optional<Int?> | |
var b: Int? { | |
get { | |
if self.lazy_b == nil { | |
let v = { return Bar.y++ }() | |
self.lazy_b = .Some(.Some(v)) | |
} | |
return self.lazy_b! | |
} | |
set { | |
self.lazy_b = .Some(newValue) | |
} | |
} | |
} | |
let g = Bar() | |
print(g.b) | |
g.b = nil | |
print(g.b) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment