迭代弱引用数组,其中对象符合 Swift 中的协议

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

我想将对象存储在一个数组中,其中对象是弱的,并且符合协议。但是当我尝试循环它时,出现编译器错误:

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()
}

知道这是怎么回事吗?

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

泛型并不像您想象的那样对其解析类型进行协议继承。您的 Weak<ClassWithReloadFRC> 类型通常是无用的。例如,你不能制作一个,更不用说加载它们的数组了。

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

我认为要问问自己的是你真正想做什么。例如,如果您要查找弱引用对象数组,可以使用内置的 Cocoa 方法。

我在 Xcode 6.4 中看到类似的编译器错误。我需要一组弱协议来为一个视图控制器存储多个委托。根据我发现的对类似问题的回答,我使用了 NSHashtable 而不是 swift 数组。

private var _delegates = NSHashTable.weakObjectsHashTable()

我认为有一个编译器limitation/bug。如果您将协议标记为 @objc 它将起作用,例如:

// Array of weak references of a protocol OK so long as protocol marked @objc
struct WeakReference<T: AnyObject> {
    weak var value: T?
}
@objc protocol P { // Note @objc, class or AnyObject won't work
    var i: Int { get }
}
class CP: P {
    var i: Int = 0
}
let cP = CP() // Strong reference to prevent collection
let weakPs: [WeakReference<P>] = [WeakReference(value: cP)] // Note typed as `[WeakReference<P>]`
print("P: \(weakPs[0].value!.i)") // 0

很烦人的是你必须使用@objc,因此不是一个纯粹的 Swift 解决方案,但因为我在 iOS 对我来说不是问题。