Skip to content

Instantly share code, notes, and snippets.

@godrm
Last active November 14, 2019 06:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save godrm/4ae9bbcb322831d67b10d0a0b4ceb232 to your computer and use it in GitHub Desktop.
Save godrm/4ae9bbcb322831d67b10d0a0b4ceb232 to your computer and use it in GitHub Desktop.
struct User {
var username: String
private var age : Int = 1
init(username : String) {
self.username = username
}
}
var player = User(username: "Mario")
player[keyPath: \User.username] = "Link"
//player[keyPath: \User.age] = 10 // Error
//player.username = "Link"
let nameKeyPath : WritableKeyPath<User, String> = \User.username
player[keyPath: nameKeyPath] = "Luigi"
//nested
struct Address {
//let street: String
var street: String {
didSet {
//
}
}
}
struct ShoppingUser {
//let address: Address
var address: Address
}
var x : KeyPath<ShoppingUser, Int> = \ShoppingUser.address.street.count
var street : WritableKeyPath<ShoppingUser, String> = \ShoppingUser.address.street
var mindy = ShoppingUser(address: Address(street: "gangnam"))
//print(mindy[keyPath: x])
mindy[keyPath: street] = "yongsan"
//Class
var pointer : AnyObject
class Student : NSObject {
var address: Address
@objc dynamic var age : Int = 5
init(street: String) {
self.address = Address(street: street)
}
func sleep() {
age += 10
}
}
var oowl = Student(street: "gangnam")
var oopath : ReferenceWritableKeyPath<Student, String> = \Student.address.street
//print(oowl.value(forKeyPath: "age"))
//oowl.setValue(10, forKey: "age")
pointer = oowl
class Teacher : NSObject {
override init() {
super.init()
// oowl.addObserver(self, forKeyPath: "address.street", options: [.initial, .new, .old], context: nil)
oowl.addObserver(self, forKeyPath: "age", options: [.new], context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
print("observer = \(object) \(keyPath) \(change)")
}
}
let teacher = Teacher.init()
oowl.sleep()
// Partial
struct GameUser {
var name : String
var age : Int
var quote : Float
}
// String
let a: PartialKeyPath<GameUser> = \GameUser.name
// Int
let b: PartialKeyPath<GameUser> = \GameUser.age
// Float
let c: PartialKeyPath<GameUser> = \GameUser.quote
func acceptKeyPath (_ keyPath: PartialKeyPath<GameUser>) {
//
}
// AnyKeyPath
let keyPaths: [AnyKeyPath] = [\User.username, \String.count]
//Composition
// ShoppingUser -> address
let addressKeyPath = \ShoppingUser.address
// Address -> street
let streetKeyPath = \Address.street
// User -> address -> street
let userStreetKeyPath = addressKeyPath.appending(path: streetKeyPath)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment