Inspired by the blog by Scott Birksted, Copyable is a Swift Macro used to bring Kotlin's copy
functionality on data classes to Swift's structs.
Creates a new instance of the struct with all properties copied from the original, allowing selective modification of specific properties while keeping others unchanged
In Package.swift
:
dependencies: [
.package(url: "https://github.com/hootsuite/copyable-macro.git", from: "1.0.0")
]
import Copyable
@Copyable
struct Student {
let name: String
let grade: Int
}
let student1 = Student(name: "Matthew", grade: 100)
print("name: \(student1.name) grade: \(student1.grade))
This should print: "name: Matthew grade: 100"
let student 2 = student1.copy { student in
student.name = "Henry"
}
print("name: \(student2.name) grade: \(student2.grade))
This should print: "name: Henry grade: 100"