Last active
April 2, 2024 13:42
-
-
Save nicholascross/8285cef20b1f5f171557478647cc0cdd to your computer and use it in GitHub Desktop.
Swift dictionary with weak references simple example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct WeakBox<ItemType: AnyObject> { | |
weak var item: ItemType? | |
init(item: ItemType?) { | |
self.item = item | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Example { | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment