This SO post explains pretty well how to solve the issue of creating a delegate
that is weak
.
Essentially, there are 2 approaches:
Using the @objc
keyword:
@objc protocol MyClassDelegate {
}
class MyClass {
weak var delegate: MyClassDelegate?
}
Using the :class
keyword:
protocol MyClassDelegate: class {
}
class MyClass {
weak var delegate: MyClassDelegate?
}
I am trying to do some research to understand what exactly the differences between the two approaches are. The docs are pretty clear about using @objc
:
To be accessible and usable in Objective-C, a Swift class must be a descendant of an Objective-C class or it must be marked @objc
.
However, nowhere I found some information about what :class
actually does. Considering the whole notion in detail, it actually doesn't make a lot of sense to. My understanding is that class
is a keyword in Swift to declare classes. So, here it seems like we are using the keyword class
itself as a protocol (as we're appending it after the :
after the protocol declaration).
So, why does this even work syntactically and what exactly does it do?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…