Mobile Development Swift Subjective
Oct 04, 2025

Explain protocols and protocol-oriented programming in Swift.

Detailed Explanation
Protocols define blueprints of methods, properties, and requirements that types can adopt.\n\n• **Protocol Basics:**\n• Define requirements without implementation\n• Can be adopted by classes, structs, and enums\n• Support inheritance and composition\n• Enable polymorphism and abstraction\n\n\nprotocol Drawable {\n var area: Double { get }\n func draw()\n}\n\nstruct Circle: Drawable {\n let radius: Double\n \n var area: Double {\n return Double.pi * radius * radius\n }\n \n func draw() {\n print("Drawing a circle")\n }\n}\n\n\n• **Protocol Extensions:**\n• Provide default implementations\n• Add functionality to existing types\n• Enable protocol-oriented programming\n\n\nextension Drawable {\n func describe() {\n print("Area: \(area)")\n }\n}\n\n\n• **Associated Types:**\n\nprotocol Container {\n associatedtype Item\n func addItem(_ item: Item)\n}\n
Discussion (0)

No comments yet. Be the first to share your thoughts!

Share Your Thoughts
Feedback