How to use Swift learning-enumeration
Use syntax for enumerations:
bs
func simpleDescription ()-> String {
switch self {
case .Spades:
return "spades"
case .Hearts:
return "hearts"
case .Diamonds:
return "dismonds"
case .Clubs:
return "clubs"
}
}
}
let hearts = Suit.Hearts // by gashero
let heartsDescription = hearts.simpleDescription ()
Note
Exercise
Add a color method to Suit and return "black" for spades and clubs, and return "red" for hearts and diamounds.
Note the above two methods of quoting Hearts members: When assigning to the hearts constant, the enum member Suit.Hearts is referenced by full name because the constant has no explicit type. In the switch, the enumeration is referenced by .Hearts because the value of self is known. You can use the convenient method at any time.
Use struct to create a structure. Structures support many of the same behaviors as classes, including methods and constructors. One important difference is that code is always copied (passed by value), while classes are passed by reference.
struct Card {
var rank: Rank
var suit: Suit
func simpleDescription ()-> String {
return "The \ (rank.simpleDescription ()) of (suit.simpleDescription ())"
}
}
let threeOfSpades = Card (rank: .Three, suit: .Spades)
let threeOfSpadesDescription = threeOfSpades.simpleDescription ()
Note
Exercise
Add methods to the Card class to create a table of cards, each of which has a combined rank and suit. (Just a typist's job, by gashero).
An enumerated instance member can own the value of the instance. The same enum member instance can have different values. You assign a value when you create an instance. The difference between the specified value and the original value: The original value of the enumeration is the same as its instance. You provide the original value when you define the enumeration.
For example, suppose a situation requires the sun's rise and fall times to be obtained from a server. The server can respond to the same message or some error messages.
enum ServerResponse {
case Result (String, String)
case Error (String)
}
let success = ServerResponse.Result ("6:00 am", "8:09 pm")
let failure = ServerResponse.Error ("Out of cheese.")
switch success {
case let .Result (sunrise, sunset):
let serverResponse = "Sunrise is at \ (sunrise) and sunset is at \ (sunset)."
case let .Error (error):
let serverResponse = "Failure ... \ (error)"
}
Note
Exercise
Add a third case to ServerResponse to choose from.
Note that the sunrise and sunset times are actually selected from a partial match to ServerResponse.
Getting started with the Swift programming language