Monday, May 16, 2016

Enumerations

The code below is tested with IBM Swift Sandbox (version 3.0-dev).

enum Numbers: Int {
    case zero, one, two, three, four, five
}

//show string
print(Numbers.one)
print(Numbers.three)
print(Numbers.five)
print("\n")

//show value
print(Numbers.one.rawValue)
print(Numbers.three.rawValue)
print(Numbers.five.rawValue)
print("\n")

//value to string
print(Numbers(rawValue: 3)!)
print(Numbers(rawValue: 4)!)
print(Numbers(rawValue: 5)!)
print("\n")

//Without the Int type
enum Names {
    case Tom, Jerry, Mickey, Donald
}

print(Names.Tom)
print(Names.Jerry)
print("\n")

//enumeration with function
func showName(name: Names) {
    print("I like \(name).")
}

showName(Names.Mickey)
showName(Names.Donald)

Console output:

one
three
five

1
3
5

three
four
five

Tom
Jerry

I like Mickey.
I like Donald.

No comments:

Post a Comment