I'd like to store an array of weak references in Swift. The array itself should not be a weak reference - its elements should be. I think Cocoa NSPointerArray
offers a non-typesafe version of this.
相关问题
- CALayer - backgroundColor flipped?
- Core Data lightweight migration crashes after App
- “Zero out” sensitive String data in Swift
- back button text does not change
- SwiftUI: UIImage (QRCode) does not load after call
相关文章
- 现在使用swift开发ios应用好还是swift?
- Using if let syntax in switch statement
- TCC __TCCAccessRequest_block_invoke
- xcode 4 garbage collection removed?
- Unable to process app at this time due to a genera
- Enum with associated value conforming to CaseItera
- Swift - hide pickerView after value selected
- Is there a Github markdown language identifier for
It's kind of late for party, but try mine. I implemented as a Set not an Array.
WeakObjectSet
Usage
Beware that WeakObjectSet won't take String type but NSString. Because, String type is not an AnyType. My swift version is
Apple Swift version 2.2 (swiftlang-703.0.18.1 clang-703.0.29)
.Code can be grabbed from Gist. https://gist.github.com/codelynx/30d3c42a833321f17d39
** ADDED IN NOV.2017
I updated the code to Swift 4
As gokeji mentioned, I figured out NSString won't get deallocated based on the code in usage. I scratched my head and I wrote MyString class as follows.
Then replace
NSString
withMyString
like this. Then strange to say it works.Then I found a strange page may be related to this issue.
https://bugs.swift.org/browse/SR-5511
It says the issue is
RESOLVED
but I am wondering if this is still related to this issue. Anyway, Behavior differences between MyString or NSString are beyond this context, but I would appreciate if someone figured this issue out.You can do this by creating a wrapper object to hold a weak pointer.
And then using these in the array
Details
xCode 9.1, Swift 4
Solution
Usage
Full Sample
Result
Other answers have covered the generics angle. Thought I'd share some simple code covering the
nil
angle.I wanted a static array (read occasionally) of all the
Label
s that currently exist in the app, but didn't want to seenil
's where the old ones used to be.Nothing fancy, this is my code...
Yet another solution to the same problem... the focus of this one is on storing a weak reference to an object but allowing you to store a struct too.
[I'm not sure how useful it is, but it did take a while to get the syntax right]
I based this on @Eonil 's work, since I loved the closure weak-bind strategy, but I did not want to use a function operator for a variable, since it felt extremely counter intuitive
What I did, instead, is as follows:
This way you can do something such as: