Weak and Unowned as native Swift types. inspire by https://github.com/nvzqz/Weak
Swift allows for weak
and unowned
bindings to objects out-of-the-box, but they can't be used just anywhere.
-
They can't be used as associated values of enum cases.
-
They can't be passed as a parameter to a function, method, or initializer without increasing the reference count.
Weak solves these two problems by giving you full control over how you want to pass around weak
or unowned
references.
- Platforms:
- macOS 10.9+
- iOS 8.0+
- watchOS 2.0+
- tvOS 9.0+
- Linux
- Xcode 8.0
- Swift 3.0
The Swift Package Manager is a decentralized dependency manager for Swift.
-
Add the project to your
Package.swift
.import PackageDescription let package = Package( ... dependencies: [ ... .Package(url: "https://github.com/ytyubox/Weak.git", from: "1.0.0"), ], targets: [ .target( name: "...", dependencies: ["Weak"]) )
-
Import the Weak module.
import Weak
A Weak<T>
instance acts just how weak var foo: T
would. When the reference count hits 0, the object
property
becomes nil
.
let weakRef: Weak<SomeClass>
do {
let instance = SomeClass()
weakRef = Weak(instance)
print(weakRef.object == nil) // false
}
print(weakRef.object == nil) // true
An Unowned<T>
instance should only be used when it will not outlive the life of object
. Otherwise, accessing
object
will cause a crash, just like accessing any unowned
reference after the reference count hits 0.
let unownedRef: Unowned<SomeClass>
do {
let instance = SomeClass()
unownedRef = Unowned(instance)
print(unownedRef.object) // SomeClass(...)
}
print(unownedRef.object) // CRASHES
Weak is released under the MIT License.