Skip to content

Instantly share code, notes, and snippets.

@davidrhyswhite
Last active June 22, 2017 23:47
Show Gist options
  • Save davidrhyswhite/18c46b859c579ef9990ec0eaeae3d15e to your computer and use it in GitHub Desktop.
Save davidrhyswhite/18c46b859c579ef9990ec0eaeae3d15e to your computer and use it in GitHub Desktop.
let decoder = JSONDecoder()
if let decoded = try? decoder.decode(Episode.self, from: encoded) {
print(decoded.title)
}
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)
}
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])")
}
}
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