8
votes

I have a class in swift that needs to have a weak pointer to an array of objects that is allocated in another class. 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]'

I also tried to no avail:

weak var avatars : [UIImageView?]?
3

3 Answers

29
votes

Weak Cannot be applied to non-class type:

It means you can’t have a weak reference to any value type instance(e.g. Array, Dictionary, String, etc…) because these all are struct not class. You only give weak reference which are of class-type(e.g 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.

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 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

9
votes

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. You can't have a weak reference to a struct instance; it's a value type, so it doesn't do weak memory management.

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. You've already declared this an Optional array; that is enough, surely.

2
votes

You're trying to apply weak to an Array of type UIImageView. Array is a struct.