class Person { }
extension Person {
private static var age_key = false //占一个字节,省空间
private static var weight_key = false //占一个字节,省空间
// private static var age_key1: Void? //这种方式也是可以的
// private static var weight_key1: Void?
var age: Int {
get {
objc_getAssociatedObject(self, &Self.age_key) as! Int
}
set {
// self abc 都相当于是key
objc_setAssociatedObject(self, &Self.age_key, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN)
}
}
var weight: Int {
get {
objc_getAssociatedObject(self, &Self.weight_key) as! Int
}
set {
// self abc 都相当于是key
objc_setAssociatedObject(self, &Self.weight_key, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN)
}
}
}
var p = Person()
p.age = 10
print(p.age)
p.weight = 50
print(p.weight)
–EOF–