Created
May 20, 2015 15:15
-
-
Save AndyDentFree/3311d77faf2c614d772b to your computer and use it in GitHub Desktop.
typeVariantsDemo 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
// 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