swift-property-name

1.0

Swift Macro for automatically generating methods to retrieve property names as strings in a type-safe manner.
CuriositySoftware/swift-property-name

What's New

v1.0

2023-12-04T11:12:44Z

swift-property-name

Build Swift Package Manager License

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.

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-name

For 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"
        )
    ]
)

Description

  • Swift Tools 5.9.0
View More Packages from this Author

Dependencies

Last updated: Fri Oct 18 2024 08:28:14 GMT-0900 (Hawaii-Aleutian Daylight Time)