用于 关联对象 的实用程序接口。如果使用它,您可以在扩展中附加任何变量。
protocol Animal {}
enum AnimalPropertyKeys: String, ExtensionPropertyKey {
case name
}
final class Dog: Animal {}
extension Dog: ExtensionProperty {}
// Declare setter and getter to property
extension Animal where Self: ExtensionProperty {
var name: String {
get {
return getProperty(key: AnimalPropertyKeys.name, defaultValue: "")
}
set {
setProperty(key: AnimalPropertyKeys.name, newValue: newValue)
}
}
}
let dog = Dog()
// You can assign string to dog.name
dog.name = "Autumn"
请查看并尝试单元测试。
如果您正在使用 Carthage,只需将 ExtensionProperty 添加到您的 Cartfile
中
github "cats-oss/ExtensionProperty"
ExtensionProperty 可通过 CocoaPods 获取。要安装它,只需将以下行添加到您的 Podfile 中
pod 'ExtensionProperty'
如果您正在使用 Swift Package Manager,只需将 ExtensionProperty 添加到您的 Package.swift
中
dependencies: [
.package(url: "https://github.com/cats-oss/ExtensionProperty", from: "1.0.2")
]
ExtensionProperty 在 MIT 许可证下可用。有关更多信息,请参阅 LICENSE 文件。