Weak
Weak and Unowned as native Swift types.
The Problem
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.
Installation
Compatibility
- Platforms:
- macOS 10.9+
- iOS 8.0+
- watchOS 2.0+
- tvOS 9.0+
- Linux
- Xcode 8.0
- Swift 3.0
Install Using Swift Package Manager
The Swift Package Manager is a decentralized dependency manager for Swift.
-
Add the project to your
Package.swift
.import PackageDescription let package = Package( name: "MyAwesomeProject", dependencies: [ .Package(url: "https://github.com/nvzqz/Weak.git", majorVersion: 1) ] )
-
Import the Weak module.
import Weak
Install Using CocoaPods
CocoaPods is a centralized dependency manager for Objective-C and Swift. Go here to learn more.
-
Add the project to your Podfile.
use_frameworks! pod 'Weak', '~> 1.0.0'
If you want to be on the bleeding edge, replace the last line with:
pod 'Weak', :git => 'https://github.com/nvzqz/Weak.git'
-
Run
pod install
and open the.xcworkspace
file to launch Xcode. -
Import the Weak framework.
import Weak
Install Using Carthage
Carthage is a decentralized dependency manager for Objective-C and Swift.
-
Add the project to your Cartfile.
github "nvzqz/Weak"
-
Run
carthage update
and follow the additional steps in order to add Weak to your project. -
Import the Weak framework.
import Weak
Install Manually
Simply add the Weak.swift
and Unowned.swift
files into your project.
Usage
Weak References
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
Unowned References
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(weakRef.object) // SomeClass(...)
}
print(unownedRef.object) // CRASHES
License
Weak is released under the MIT License.