Skip to content

A collection of Swift Macros to automate code generation tasks in Swift

License

Notifications You must be signed in to change notification settings

matteo-pacini/ZPMacros

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ZPMacros

ZPMacros is a collection of Swift Macros to assist with Swift development.

These macros aim to streamline and enhance the development process by automating code generation tasks.

Table of Contents

Installation

To get started with ZPMacros, add it to your SwiftPM dependencies:

dependencies: [
    .package(url: "https://github.com/matteo-pacini/ZPMacros.git", .branch("master"))
]

Macros

WrapWithCombine

This macros generates a protocol extension, where all methods are wrapped for Combine (Deferred and Future).

This supports generics, async and throws.

To trigger it, annotate a protocol with @WrapWithCombine, i.e.:

@WrapWithCombine
protocol A {
    func test() async throws -> String
}

// ...will expand to...

protocol A {
    func test() async throws -> String
}

extension A {
    func test() -> AnyPublisher<String, any Error> {
        Deferred {
            Future { promise in
                Task {
                    do {
                        let result: String = try await test()
                        promise(.success(result))
                    } catch {
                        promise(.failure(error))
                    }
                }
            }
        }
        .eraseToAnyPublisher()
    }
}

To refine the error type, use the @WrapWithCombine(error:) alternative, i.e:

@WrapWithCombine(error: SomeError.self)
protocol A {
    func test() async throws -> String
}

// ...will expand to...

@WrapWithCombine(error: SomeError.self)
protocol A {
    func test() async throws -> String
}

extension A {
    func test() -> AnyPublisher<String, SomeError> {
        Deferred {
            Future { promise in
                Task {
                    do {
                        let result: String = try await test()
                        promise(.success(result))
                    } catch let error as SomeError {
                        promise(.failure(error))
                    } catch {
                        fatalError("Unkown error propagated: \(String(describing: type(of: error)))")
                    }
                }
            }
        }
        .eraseToAnyPublisher()
    }
}

Known issues

  • SwiftSyntax has to be compiled when adopting this package, compilation times are going to increase because of this

Contributing

Contributions are more than welcome!

License

This project is licensed under the MIT License - see the LICENSE file for details.

About

A collection of Swift Macros to automate code generation tasks in Swift

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages