This Swift macro simplifies the process of obtaining property names as strings in Swift. By annotating a struct or class with @PropertyNameAccessible
, it automatically generates extensions and methods that provide access to property names as strings.
To get started, import: import PropertyName
, annotate your struct or class with @PropertyNameAccessible
:
import PropertyName
@PropertyNameAccessible
struct Person {
let name: String
let age: Int
let email: String
let isEmployee: Bool
}
This will automatically generate an extension with a propertyName(for:)
function.
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()
}
}
}
Usage examples are as follows:
print(Person.propertyName(for: \.name)) // => "name"
print(Person.propertyName(for: \.age)) // => "age"
print(Person.propertyName(for: \.email)) // => "email"
print(Person.propertyName(for: \.isEmployee)) // => "isEmployee"
If you are using GUI to set up Package Dependencies in Xcode, add the URL in Package Dependencies.
https://github.com/CuriositySoftware/swift-property-name
If you are using Package.swift add:
.package(
url: "https://github.com/CuriositySoftware/swift-property-name/",
.upToNextMajor(from: "0.1.0")
)
and then add the product to any target that needs access to the macro:
.target(
name: "YourTarget",
dependencies: [
.product(
name: "PropertyName",
package: "swift-property-name"
)
]
)