Extension Property
用于关联对象的实用接口。如果您使用它,可以在扩展中附加任何变量。
用法
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
如果您正在使用Carthage,只需将ExtensionProperty添加到您的Cartfile
中。
github "cats-oss/ExtensionProperty"
CocoaPods
ExtensionProperty可通过CocoaPods获取。要安装,只需将以下行添加到您的Podfile中。
pod 'ExtensionProperty'
Swift 包管理器
如果您正在使用 Swift 包管理器,只需在您的 Package.swift
中添加 ExtensionProperty 即可。
dependencies: [
.package(url: "https://github.com/cats-oss/ExtensionProperty", from: "1.0.2")
]
要求
- Xcode 9.3
- Swift 4.1 或更高版本
许可
ExtensionProperty 在 MIT 许可下提供。有关更多信息,请参阅 LICENSE 文件。