Skip to content

Instantly share code, notes, and snippets.

@foxicode
Created August 21, 2023 13:22
Show Gist options
  • Save foxicode/d1ca4db634381b92b8cbe93c6a58e05a to your computer and use it in GitHub Desktop.
Save foxicode/d1ca4db634381b92b8cbe93c6a58e05a to your computer and use it in GitHub Desktop.
Existentials in Swift
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