
VIPER Design Pattern - some questions
By Omer Cagri Sayir•
Note: In this post, everything is my note. So it may be wrong information.
AnyObject
Q: Why are we marking some protocols with : AnyObject
?
In Swift, marking a protocol with : AnyObject
makes it a class-constrained protocol, meaning that only class types (not structs or enums) can conform to it.
There are some reasons for that,
- Weak References: If you need to store a reference to something that conforms to your protocol as weak, the protocol must be restricted to class types (objects). This is because only objects can be referenced weakly.
- ARC (Automatic Reference Counting)
Where Self
In Swift, Self in a protocol extension refers to the concrete type that is conforming to that protocol.
extension ViewProtocol where Self: UIViewController { }
It means: This extension only applies to types that conform to ViewProtocol and are also subclasses of UIViewController.
So, any class that adopts ViewProtocol and inherits from UIViewController will gain the default implementations defined in that extension. If a type conforms to ViewProtocol but isn’t a UIViewController, it won’t get those default implementations.