Last active
June 22, 2017 23:47
-
-
Save davidrhyswhite/18c46b859c579ef9990ec0eaeae3d15e to your computer and use it in GitHub Desktop.
This file contains hidden or 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
let decoder = JSONDecoder() | |
if let decoded = try? decoder.decode(Episode.self, from: encoded) { | |
print(decoded.title) | |
} |
This file contains hidden or 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
struct Episode: Codable { | |
var id: String | |
var title: String | |
var live: Bool | |
} | |
let whiteGold = Episode(id: 'p050hssx', title: 'White Gold', live: false) | |
let encoder = JSONEncoder() | |
if let encoded = try? encoder.encode(whiteGold) { | |
print(encoded) | |
} |
This file contains hidden or 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 MyObject: NSObject { | |
private var observerContext = 0 | |
var objectToObserve = Foo() | |
override init() { | |
super.init() | |
objectToObserve.addObserver(self, forKeyPath: #keyPath(Foo.bar), options: [.new, .old], context: &observerContext) | |
} | |
deinit { | |
objectToObserve.removeObserver(self, forKeyPath: #keyPath(Foo.bar), context: &observerContext) | |
} | |
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { | |
guard context == &observerContext else { | |
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) | |
return | |
} | |
// do something upon notification of the observed object | |
print("\(keyPath): \(change?[.newKey])") | |
} | |
} |
This file contains hidden or 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: NSObject { | |
@objc dynamic var bar = 0 | |
} | |
class MyObject { | |
private var token: NSKeyValueObservation | |
var objectToObserve = Foo() | |
init() { | |
token = objectToObserve.observe(\.bar) { object, change in | |
print("bar property is now \(object.bar)") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment