迭代弱引用的数组,其中对象符合Swift中的协议 [英] Iterate array of weak references where objects conform to a protocol in Swift

查看:71
本文介绍了迭代弱引用的数组,其中对象符合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?

位广播需要相同宽度的类型%.asSubstituted =位广播i64 %35到i128,!dbg!5442 LLVM错误:发现损坏的函数,编译 流产了!

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

推荐答案

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

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

我认为要问自己的事情是您确实正在尝试做的事情.例如,如果您要跟踪一系列弱引用的对象,则可以使用内置的Cocoa方法来实现.

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.

这篇关于迭代弱引用的数组,其中对象符合Swift中的协议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆