Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does enum retain its associated object?

Tags:

swift

I am curious if the next code will lead to the strong reference cycle?

enum Type {
    case some(obj:Any)
}

class Entity {
    var type:Type
    init() {
      type = Type.some(obj:self)
    }
}
like image 513
Mykola Denysyuk Avatar asked Jun 26 '17 17:06

Mykola Denysyuk


1 Answers

Yes. Any is implicitly strong. If you pass a reference type, it will be a strong reference. It's not quite a "cycle" since nothing "retains" an enum, but as long as the value exists (or any copy of the value), it will hold onto Entity and prevent it from being deallocated.

Imagine if it were not true. What would .some(obj: NSObject()) contain? If Type.some did not increase the retain count, the NSObject would vanish. (Since this is very similar to an Optional, that would be very surprising, since many T? would immediately become nil.)

BTW, this is easily and usefully explored by creating a deinit method on Entity.

like image 110
Rob Napier Avatar answered Oct 21 '22 19:10

Rob Napier