SwiftCopy
A Swift Package that provides a convenient, Kotlin-like way to copy immutable instances of Swift types such as struct
.
Usage
Simply conform your structs to the Copyable
protocol.
struct User: Copyable {
let id: Int
let firstName: String
let lastName: String
let created: Date
}
let myUser = User(id: "123", firstName: "David", lastName: "Scheutz", created = .now)
// Copy the instance by changing the `firstName` and `lastName` properties
let updatedUser = myUser.copy(firstName: "Your", lastName: "Name")
Optional Properties Support
SwiftCopy
wraps optional properties using the OptionalCopy
enum providing explicit control over how to update or reset it’s state.
public enum OptionalCopy<T> {
case update(T)
case reset
case noChange // default value used by the copy function
}
struct User: Copyable {
let id: Int
let name: String
let profilePicture: String?
}
let myUser = User(id: "123", name: "David", profilePicture: nil)
// Copy the instance by setting the `profilePicture`
_ = myUser.copy(profilePicture: .update("https://dave.com/pictures/214381"))
// Copy the instance by resetting the `profilePicture`
_ = myUser.copy(profilePicture: .reset)
// Copy the instance by using an optional type directly
let optionalValue: String? = "Value"
_ = myUser.copy(profilePicture: .use(optionalValue))
Installation
1. Add Swift Package
You can use the Swift Package Manager to install SwiftCopy
by adding it as a dependency to your Package.swift
file:
dependencies: [
.package(url: "[email protected]:davidscheutz/SwiftCopy.git", from: "1.0.0")
]
Make sure to add SwiftCopy
as a dependency to your Target.
2. Add SwiftCopy CodeGeneratorPlugin as Build Tool Plugin
Select your Project -> Your Target -> Build Phases -> Add CodeGeneratorPlugin (SwiftCopy)
Demo Project
Feel free to take a look at the SwiftCopyDemo.xcodeproj
to see the library in action.
Contributing
Contributions to SwiftCopy are welcomed and encouraged!
It is easy to get involved. Open an issue to discuss a new feature, write clean code, show some love using unit tests and open a Pull Request.
A list of contributors will be available through GitHub.
PS: Check the open issues and pull requests for existing discussions.
License
SwiftCopy is available under the MIT license. See LICENSE for more information.
Credit
This project uses Sourcery for the code generation.