Skip to content

Instantly share code, notes, and snippets.

@nicholascross
Last active April 2, 2024 13:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicholascross/8285cef20b1f5f171557478647cc0cdd to your computer and use it in GitHub Desktop.
Save nicholascross/8285cef20b1f5f171557478647cc0cdd to your computer and use it in GitHub Desktop.
Swift dictionary with weak references simple example
struct WeakBox<ItemType: AnyObject> {
weak var item: ItemType?
init(item: ItemType?) {
self.item = item
}
}
//
// WeakBox.swift
// Injectable
//
// Created by Nicholas Cross on 9/2/19.
// Copyright © 2019 Nicholas Cross. All rights reserved.
//
import XCTest
class WeakBoxExampleTests: XCTestCase {
func testWeakDictionary() {
var weakDictionary: [String: WeakBox<Example>] = [:]
var example: Example? = Example()
weakDictionary["example"] = WeakBox(item:example)
XCTAssertNotNil(weakDictionary["example"]?.item)
example = nil
XCTAssertNil(weakDictionary["example"]?.item)
}
}
class Example {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment