Created
August 21, 2023 13:22
-
-
Save foxicode/d1ca4db634381b92b8cbe93c6a58e05a to your computer and use it in GitHub Desktop.
Existentials in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protocol Shape { | |
associatedtype NumericType | |
func area() -> NumericType | |
} | |
struct Rectangle: Shape { | |
typealias NumericType = Double | |
var width: Double | |
var length: Double | |
func area() -> Double { | |
width * length | |
} | |
} | |
struct IntSquare: Shape { | |
typealias NumericType = Int | |
var side: Int | |
func area() -> Int { | |
side * side | |
} | |
} | |
var shape: any Shape = Rectangle(width: 3, length: 4) | |
print(shape.area()) | |
shape = IntSquare(side: 5) | |
print(shape.area()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment