扩展属性

platforms Swift4.1 License
Carthage SwiftPM Version

用于 关联对象 的实用程序接口。如果使用它,您可以在扩展中附加任何变量。

用法

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 Package Manager

如果您正在使用 Swift Package Manager,只需将 ExtensionProperty 添加到您的 Package.swift

dependencies: [
    .package(url: "https://github.com/cats-oss/ExtensionProperty", from: "1.0.2")
]

要求

许可证

ExtensionProperty 在 MIT 许可证下可用。有关更多信息,请参阅 LICENSE 文件