✨ Add associated property for extension of protocol or class
Add associated property for extension of protocol
protocol FullNamed: class {
var name: String {get set}
}
extension FullNamed where Self: AssociatedCompatible {
var name: String {
get {
return self.associated.value(default: "")
}
set {
self.associated.setValue(newValue)
}
}
}
class Person: FullNamed, AssociatedCompatible {
}
let person: FullNamed = Person()
person.name = "roger"
let name = person.name
XCTAssertEqual(name, "roger")
- You can use
Associated
to all ofNSObject
subclasses.
class Animal: NSObject {
}
extension Animal: FullNamed {
}
extension Animal {
var age: Int? {
get {
return self.associated.value()
}
set {
self.associated.setValue(newValue)
}
}
}
let animal = Animal()
animal.age = 100;
let age = animal.age
XCTAssertEqual(age, 100)
- Using Swift Package Manager:
import PackageDescription
let package = Package(
name: "MyAwesomeApp",
dependencies: [
.Package(url: "https://github.com/IMFWorks/Associated", majorVersion: 1),
]
)
Associated is under Apache license. See the LICENSE file for more info.