Enumerations are no new additions to programming language. They have always been there from age old days. But what has changed in SWIFT's enumeration are somethings that we have taken for granted in the past. Like default constant values associated with enumeration values. In addition, handling range values (New in SWIFT), having function definitions and also initializing with init methods.
enum Rank {
case One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
case Jack
case Queen
case King
case Ace
func rankDescription() -> String {
switch self {
case .One, .Two, .Three, .Four, .Five, .Six, .Seven, .Eight, .Nine, .Ten:
return "Numbers"
case .Jack:
return "Jack"
case .Queen:
return "Queen"
case .King:
return "King"
case .Ace:
return "Ace"
}
}
}
enum Suit {
case Hearts, Clubs, Diamonds, Spades
case Others
func suitDescription()->String {
switch self {
case Hearts:
return "Heart of hearts"
case Clubs:
return "Beat the hell out of your enemy"
case Diamonds:
return "You are the richest of all"
case Spades:
return "You are the truest of all"
case Others:
return "Not sure, why you folks are here"
}
}
func colorForCards()->String {
switch self {
case Hearts, Diamonds:
return "Red"
case Clubs, Spades, Others:
return "Black"
}
}
}
let myCard = Suit.Diamonds
print("Card description: \(myCard.suitDescription())")
print("Card description: \(myCard.colorForCards())")
struct Card {
var rank: Rank
var suit: Suit
func cardDescription() -> String {
return "The rank is:\(rank.rankDescription()) and suit is: \(suit.suitDescription()) with color \(suit.colorForCards())"
}
}
let threeOfSpades = Card(rank: .King, suit: .Diamonds)
print(threeOfSpades.cardDescription())
/*
* Use this to process response from remote service and invoke appropriate functions
*/
enum Response {
case success(String, String)
case Failure(String)
}
let successServerResponse = Response.success("http://www.google.com", "{searchResult:{[result1:virtusa, result2:something, result3:anotherthing]}}")
let failureServerResponse = Response.Failure("Failed to fetch any results")
func processResponse( response:Response) {
switch(response) {
case let .success(searchURL, searchResult):
print("URL: \(searchURL) and response is: \(searchResult)")
case let .Failure(error):
print("Erorr is: \(error)")
}
}
processResponse(successServerResponse)
let shoppingList = ["Shell for MacBook", "Wireless mouse", "Raspberry Pi - B"]
for item in shoppingList {
print("Items to buy \(item)")
}
No comments:
Post a Comment