Mobile Development Swift Subjective
Oct 04, 2025

How does Swift's type system handle variance?

Detailed Explanation
Swift's type system handles variance through careful design of generic constraints and protocols.\n\n• **Variance Types:**\n• **Covariance:** Subtype can be used where supertype expected\n• **Contravariance:** Supertype can be used where subtype expected\n• **Invariance:** Exact type match required\n\n• **Swift's Approach:**\n\n// Swift arrays are invariant\nclass Animal { }\nclass Dog: Animal {}\n\nvar dogs: [Dog] = [Dog()]\n// var animals: [Animal] = dogs // ❌ Error - not covariant\n\n// But you can convert explicitly\nvar animals: [Animal] = dogs.map { $0 as Animal }\n\n\n• **Function Parameter Variance:**\n\n// Functions are contravariant in parameters\ntypealias DogHandler = (Dog) -> Void\ntypealias AnimalHandler = (Animal) -> Void\n\nfunc processDog(handler: DogHandler) {}\n\nlet animalHandler: AnimalHandler = { animal in }\n// processDog(handler: animalHandler) // ❌ Not allowed\n\n\n• **Protocol Variance:**\n\nprotocol Container {\n associatedtype Item\n func add(_ item: Item)\n}\n\n// Protocols with associated types are invariant\nstruct IntContainer: Container {\n func add(_ item: Int) {}\n}\n\nstruct StringContainer: Container {\n func add(_ item: String) {}\n}\n\n\n• **Workarounds:**\n\n// Use type erasure for variance-like behavior\nprotocol AnyContainer {\n func addAny(_ item: Any)\n}\n\nextension IntContainer: AnyContainer {\n func addAny(_ item: Any) {\n let intItem = item as? Int {\n add(intItem)\n }\n }\n}\n
Discussion (0)

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

Share Your Thoughts
Feedback