简体   繁体   English

weak不能应用于非类型的uiimageview

[英]weak cannot be applied to non-class type uiimageview

I have a class in swift that needs to have a weak pointer to an array of objects that is allocated in another class. 我有一个swift类,需要一个指向另一个类中分配的对象数组的弱指针。 I have 我有

class myView: UIView
{
    var lines:[CAShapeLayer] = []
    weak var avatars : [UIImageView]?

The error I get is 我得到的错误是

'weak' cannot be applied to non-class type '[UIImageView]' 'weak'不能应用于非类型'[UIImageView]'

I also tried to no avail: 我也试着无济于事:

weak var avatars : [UIImageView?]?

Weak Cannot be applied to non-class type: 弱无法应用于非类类型:

It means you can't have a weak reference to any value type instance(eg Array, Dictionary, String, etc…) because these all are struct not class. 这意味着您不能对任何值类型实例(例如,Array,Dictionary,String等)进行弱引用,因为这些都是struct而不是class。 You only give weak reference which are of class-type(eg UIImage, UIImageView, etc…).In this case, you are trying to give weak reference to UIImageView Array and we know array is a value type, so it is not possible. 你只给出了类型的弱引用(例如UIImage,UIImageView等)。在这种情况下,你试图给UIImageView数组提供弱引用,我们知道数组是一个值类型,所以它是不可能的。

For example: 例如:

weak var str: String? //CompileTime Error(Wrong)

weak var arr: Array? //CompileTime Error(Wrong)

weak var imageView: UIImageView? //Correct

In case of Protocol: If we have just a protocol of struct type: 如果是Protocol:如果我们只有struct类型的协议:

protocol SomeProtocol{
    func doSomething()  
}

We cannot declare variables of this type as weak: 我们不能将此类型的变量声明为弱:

weak var delegate: SomeProtocol? //CompileTime Error(Wrong)

But if we make protocol of class type like this: 但是如果我们像这样制作类类型的协议:

protocol SomeProtocol: class{
    func doSomething()
}

We can declare variables of this type as weak: 我们可以将这种类型的变量声明为弱:

weak var delegate: SomeProtocol? //Correct

I think you easily understand it, why this happens in protocol? 我想你很容易理解它,为什么会在协议中发生?

Same reason: You only give weak reference which are of class-type 同样的原因:你只给出了类型的弱引用

needs to have a weak pointer to an array of objects 需要有一个指向对象数组的弱指针

Well, as the error message tells you, you can't. 好吧,正如错误消息告诉你的那样,你不能。 Array is a struct, not a class. Array是一个结构,而不是一个类。 You can't have a weak reference to a struct instance; 您不能对结构实例有弱引用; it's a value type, so it doesn't do weak memory management. 它是一种值类型,因此它不会进行weak内存管理。

Nor does it need it - there is no danger of a retain cycle, because this is a value type. 它也不需要它 - 没有保留周期的危险,因为这是一种值类型。 You should ask yourself why you think it does need it. 你应该问问自己为什么你认为它确实需要它。 Perhaps you think weak and Optional always go together, but they do not. 也许你认为weak和选择总是在一起,但他们没有。 You've already declared this an Optional array; 你已经宣布这是一个Optional数组; that is enough, surely. 这当然就足够了。

You're trying to apply weak to an Array of type UIImageView . 您正在尝试将weak应用于UIImageView类型的Array Array is a struct. Array是一个结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM