Enumerations

This page is under construction. Please come back later.
#!/usr/bin/env swift;
import Foundation
import Utils
enum CompassPoint : Int {
case North
case East
case South
case West
}
func compassPointToString(_ c:CompassPoint) -> String {
var result:String = ""
switch c {
case CompassPoint.North:
result = "North"
case CompassPoint.East:
result = "East"
case CompassPoint.South:
result = "South"
case CompassPoint.West:
result = "West"
}
return result
}
func turnRight(_ c:CompassPoint) -> CompassPoint {
if c == CompassPoint.North {
return CompassPoint.East
} else if c == CompassPoint.East {
return CompassPoint.South
} else if c == CompassPoint.South {
return CompassPoint.West
} else {
return CompassPoint.North
}
}
func main() -> Void {
var cp1:CompassPoint = CompassPoint.North
print("cp1: " + String(describing: cp1))
print("SOUTH: " + compassPointToString(CompassPoint.South))
print("turnRight(cp1): " + compassPointToString(turnRight(cp1)))
let CP2:CompassPoint = CompassPoint.East
if cp1 == CP2 {
print("cp1 == cp2")
} else {
print("cp1 != cp2")
}
cp1 = CP2
if cp1 == CP2 {
print("cp1 == cp2")
} else {
print("cp1 != cp2")
}
exit(EXIT_SUCCESS)
}
main()
Output
cp1: North
SOUTH: South
turnRight(cp1): East
cp1 != cp2
cp1 == cp2
#!/usr/bin/env swift;
import Foundation
import Utils
enum Color : Int {
case Red = 1
case Green = 2
case Yellow = 3
case Blue = 4
case Magenta = 5
case Cyan = 6
}
func combineColors(_ c1:Color, _ c2:Color) -> Color {
let i1:Int = c1.rawValue
let i2:Int = c2.rawValue
let RESULT:Int = i1 | i2
let RETURN_COLOR:Color? = Color(rawValue: RESULT)!
return RETURN_COLOR!
}
func main() -> Void {
var c1:Color = Color.Blue
print("c1: " + String(describing: c1))
print("RED: " + String(describing: Color.Red))
print("combineColors(c1, RED): " + String(describing: combineColors(c1, Color.Red)))
let c2:Color = Color.Green
print("combineColors(c1, c2): " + String(describing: combineColors(c1, c2)))
if c1 == c2 {
print("c1 == c2")
} else {
print("c1 != c2")
}
c1 = c2
if c1 == c2 {
print("c1 == c2")
} else {
print("c1 != c2")
}
let BAD:Color? = Color(rawValue: 7)!
print("bad: " + String(describing: BAD))
exit(EXIT_SUCCESS)
}
main()
Output
Enums2/Enums2.swift:40: Fatal error: Unexpectedly found nil while unwrapping an Optional value
Questions
- {{Who's on first?}}
- {{Who's on second?}}
- {{Who's on third?}}
Projects
More ★'s indicate higher difficulty level.
References
- [[Swift Community]]
- [[Swift Language Guide]]
- [[Swift Language Reference]]
- [[Swift Programming Language]], Apple Inc.
- [[Swift Doc]]
- [[We Heart Swift]]
- [[Swift Cookbook]]
- [[Swift Playground]]
- [[Swift at TutorialsPoint]]
- [[Hacking with Swift]]
Pure Programmer


