Moo works with types that conform to the Copyable protocol. You should make a class conform like this
import Moo
final class SomeType: Copyable {
static func createCopy(of other: SomeType) -> SomeType { ... }
...
}
You will likely want to have your class be final in order to return a the concrete type rather than Self which is what the protocol requires. This avoids the need to use SomeNonFinalType(...) as! SomeNonFinalType as the return value and a lot of potential bugs that can come with inheritance.
Once a type is Copyable you simply applie the @COW property wrapper to the type and it will be coppied when you access the wrapped value.
If you have a type that conforms to NSCopying you can conform it to Copyable and it will use NSCopying‘s copy() function as the default implimentation of Copyable‘s requirements.
Bypassing Self Requirements
Because Copyable has Self requirements it can cause issues if you try to have a collection of them. If you need to create a copy of a type you can also drop into _createCopy(of:) which is a function at global scope. It will safely attempt to use the Copyable protocol on the object and return a copy or nil.
Moo 🐮
A package to give reference types Copy On Write (COW) symantics using Property Wrappers and no external dependencies.
Swift Package Manager
Update your
Package.swift
to include this to your package dependencies:Usage
General
Moo works with types that conform to the
Copyable
protocol. You should make a class conform like thisYou will likely want to have your class be
final
in order to return a the concrete type rather thanSelf
which is what the protocol requires. This avoids the need to useSomeNonFinalType(...) as! SomeNonFinalType
as the return value and a lot of potential bugs that can come with inheritance.Once a type is
Copyable
you simply applie the@COW
property wrapper to the type and it will be coppied when you access the wrapped value.Working with NSCopying
If you have a type that conforms to
NSCopying
you can conform it toCopyable
and it will useNSCopying
‘scopy()
function as the default implimentation ofCopyable
‘s requirements.Bypassing Self Requirements
Because
Copyable
hasSelf
requirements it can cause issues if you try to have a collection of them. If you need to create a copy of a type you can also drop into_createCopy(of:)
which is a function at global scope. It will safely attempt to use theCopyable
protocol on the object and return a copy ornil
.Acknowledgements
Thanks to: