Skip to content

Copyable is a Swift Macro used to bring Kotlin's `copy` functionality to Swift.

License

Notifications You must be signed in to change notification settings

hootsuite/copyable-macro

Repository files navigation

copyable-macro

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.

Functionality

Creates a new instance of the struct with all properties copied from the original, allowing selective modification of specific properties while keeping others unchanged

Swift Package Manager

In Package.swift:

dependencies: [
    .package(url: "https://github.com/hootsuite/copyable-macro.git", from: "1.0.0")
]

Usage

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"

Reference

A Kotlin Style .copy Function for Swift Structs

About

Copyable is a Swift Macro used to bring Kotlin's `copy` functionality to Swift.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages