CuriositySoftware/swift-property-name
Swift Macro for automatically generating methods to retrieve property names as strings in a type-safe manner.
Quick start
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"Installation
For Xcode
If you are using GUI to set up Package Dependencies in Xcode, add the URL in Package Dependencies.
https://github.com/CuriositySoftware/swift-property-nameFor Package.swift
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"
)
]
)Package Metadata
Repository: CuriositySoftware/swift-property-name
Stars: 4
Forks: 0
Open issues: 0
Default branch: main
Primary language: swift
License: MIT
Topics: swiftmacros
README: README.md