This is a collection of useful Swift macros
- Xcode 15 or higher
- Swift 5.9
Once you have your Swift package set up, adding orcam
as a dependency to the dependencies
value in Package.swift
.
.package(url: "https://github.com/trinhngocthuyen/orcam", from: "0.0.1")
Then, add Orcam
module product as a dependency of a target
's dependencies
.
.product(name: "Orcam", package: "orcam")
@Init
class Foo {
let x: Int
let y: Double?
let completion: () -> Void
}
Expanded code
class Foo {
let x: Int
let y: Double?
let completion: () -> Void
init(x: Int, y: Double? = nil, completion: @escaping () -> Void) {
self.x = x
self.y = y
self.completion = completion
}
}
@Singleton
class Foo {
}
Expanded code
class Foo {
static let shared = Foo()
private init() {
}
}
The macro still works when we explicitly declare the shared
variable.
@Singleton
class Foo {
let x: Int
static let shared = Foo(x: 0)
}
@Copyable
struct Foo {
let x: Int
let y: Int
}
Expanded code
struct Foo {
let x: Int
let y: Int
func copy(x: Int? = nil, y: Int? = nil) -> Self {
return .init(x: x ?? self.x, y: y ?? self.y)
}
}
This macro also generates a copy
function in which each property can be updated with a closure. To enable this, pass the argument closure
as true
to the macro.
@Copyable(closure: true)
struct Foo {
let x: Int
let y: Int
}
Expanded code
struct Foo {
let x: Int
let y: Int
func copy(x: Int? = nil, y: Int? = nil) -> Self {
return .init(x: x ?? self.x, y: y ?? self.y)
}
func copy(update_x: ((Int) -> Int)? = nil, update_y: ((Int) -> Int)? = nil) -> Self {
func call<V>(_ f: ((V) -> V)?, _ v: V) -> V {
f?(v) ?? v
}
return .init(x: call(update_x, self.x), y: call(update_y, self.y))
}
}