Search code examples
iosswiftautomatic-ref-countingprotocolsweak-references

Iterate array of weak references where objects conform to a protocol in Swift


I want to store objects in an array, where objects are weak, and conforms to a protocol. But when I try to loop it, I get a compiler error:

public class Weak<T: AnyObject> {
    public weak var value : T?
    public init (value: T) {
        self.value = value
    }
}

public protocol ClassWithReloadFRC: class {

    func reloadFRC()
}

public var objectWithReloadFRC = [Weak<ClassWithReloadFRC>]()

for owrfrc in objectWithReloadFRC {

    //If I comment this line here, it will able to compile.
    //if not I get error see below
    owrfrc.value!.reloadFRC()
}

Any idea what the heck?

Bitcast requires types of same width %.asSubstituted = bitcast i64 %35 to i128, !dbg !5442 LLVM ERROR: Broken function found, compilation aborted!

enter image description here enter image description here enter image description here


Solution

  • Generics don't do protocol inheritance of their resolving type in the way that you seem to imagine. Your Weak<ClassWithReloadFRC> type is going to be generally useless. For example, you can't make one, let alone load up an array of them.

    class Thing : ClassWithReloadFRC {
        func reloadFRC(){}
    }
    let weaky = Weak(value:Thing()) // so far so good; it's a Weak<Thing>
    let weaky2 = weaky as Weak<ClassWithReloadFRC> // compile error
    

    I think the thing to ask yourself is what you are really trying to do. For example, if you are after an array of weakly referenced objects, there are built-in Cocoa ways to do that.