这个 Swift 宏简化了在 Swift 中获取属性名称字符串的过程。 通过使用 @PropertyNameAccessible
注解结构体或类,它会自动生成扩展和方法,以提供对属性名称字符串的访问。
要开始使用,导入:import PropertyName
,使用 @PropertyNameAccessible
注解您的结构体或类。
import PropertyName
@PropertyNameAccessible
struct Person {
let name: String
let age: Int
let email: String
let isEmployee: Bool
}
这将自动生成一个带有 propertyName(for:)
函数的扩展。
extension Person {
static func propertyName(for keyPath: PartialKeyPath<Self>) -> String {
switch keyPath {
case \.name:
return "name"
case \.age:
return "age"
case \.email:
return "email"
case \.isEmployee:
return "isEmployee"
default:
fatalError()
}
}
}
用法示例如下
print(Person.propertyName(for: \.name)) // => "name"
print(Person.propertyName(for: \.age)) // => "age"
print(Person.propertyName(for: \.email)) // => "email"
print(Person.propertyName(for: \.isEmployee)) // => "isEmployee"
如果您使用 GUI 在 Xcode 中设置 Package Dependencies,请在 Package Dependencies 中添加 URL。
https://github.com/CuriositySoftware/swift-property-name
如果您使用 Package.swift,请添加
.package(
url: "https://github.com/CuriositySoftware/swift-property-name/",
.upToNextMajor(from: "0.1.0")
)
然后将 product 添加到任何需要访问该宏的目标中
.target(
name: "YourTarget",
dependencies: [
.product(
name: "PropertyName",
package: "swift-property-name"
)
]
)