Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@AndyDentFree
Created May 20, 2015 15:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndyDentFree/3311d77faf2c614d772b to your computer and use it in GitHub Desktop.
Save AndyDentFree/3311d77faf2c614d772b to your computer and use it in GitHub Desktop.
typeVariantsDemo in Swift
// the Swift direct equivalent of the F# gist https://gist.github.com/AndyDentFree/46ac476a31b07d103a03
import Darwin
enum Shape {
case Circle (radius:Double)
case Rectangle (width:Double, height:Double)
case Triangle (tbase:Double, height:Double)
}
func area(shape:Shape) -> Double {
switch shape {
case .Circle(let radius): return M_PI * radius * radius
case .Rectangle (let width, let height): return width * height
case .Triangle (let tbase, let height): return 0.5 * tbase * height
}
}
let cshape = Shape.Circle(radius:10.0)
println("Circle Area: %f", area(cshape))
let rshape = Shape.Rectangle(width:3.0, height:7.0)
println("Rect Area: %f", area(rshape))
let tshape = Shape.Triangle(tbase:3.0, height:7.0)
println("Triangle Area: %f", area(tshape))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment