János János - 1 year ago 123
iOS Question

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

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

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download