[英]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! Bitcast需要相同宽度%的类型.asSubstituted = bitcast i64%35到i128,!dbg!5442 LLVM ERROR:找到破碎的功能,编译中止!
I think there is a compiler limitation/bug. 我认为存在编译器限制/错误。 If you mark your protocol as @objc it will work, eg: 如果您将协议标记为@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
It is annoying that you have to use @objc and therefore not a pure Swift solution, but since I am on iOS not a problem for me. 令人讨厌的是你必须使用@objc而不是纯粹的Swift解决方案,但因为我在iOS上对我来说不是问题。
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. 你的Weak<ClassWithReloadFRC>
类型通常是无用的。 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. 例如,如果您在一组弱引用对象之后,有内置的Cocoa方法可以做到这一点。
I was seeing a similar compiler error in Xcode 6.4. 我在Xcode 6.4中看到了类似的编译器错误。 I needed an array of weak protocols to store multiple delegates for a view controller. 我需要一组弱协议来为视图控制器存储多个委托。 Based on an answer to a similar question I found, I used a NSHashtable instead of a swift array. 根据我发现的类似问题的答案,我使用了NSHashtable而不是swift数组。
private var _delegates = NSHashTable.weakObjectsHashTable()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.