If I have a protocol:
protocol SomeProtocol {
func doSomething()
}
and in a helper class, I have a reference to a protocol variable:
class someClass {
var delegate: SomeProtocol?
}
because SomeProtocol isn't marked with : class, it's assumed that delegate can be anything and in the case of value types (structs and enums) there's no need for weak var because value types can't create strong references. In fact, the compiler doesn't allow weak var on anything but class types.
However, nothing stops you from setting a class as the delegate and if the protocol isn't marked with : class (as SomeProtocol is),weak var` can't be used and that creates a retain cycle.
class MyClass: NSObject, SomeProtocol {
func doSomething() { }
}
struct MyStruct: SomeProtocol {
func doSomething() { }
}
let someClass = SomeClass()
let myStruct = MyStruct()
someClass.delegate = myStruct
// After myStruct gets assigned to the delegate, do the delegate and the struct refer to the same instance or does the struct get copied?D
let myClass = MyClass()
someClass.delegate = myClass // can't use weak var so myClass is retained
Given the above example, in the case of using delegates and datasource, shouldn't : class always be used? Basically any protocol that is used to maintain a reference should always be restricted to class objects right?
UICollectionViewhelper class with a reference to a protocol that wasn't marked class where the reference was to aUIViewController. Because the protocol wasn't a class one, the property couldn't beweakand was never being deallocated. - barndog