1. Enumeration
Create an enumeration with enum-note that the enumeration of Swift can be associated with methods:
enumRank:int { CaseAce =1 CaseThree, four, Five, Six, Seven, Eight, Nine, Ten CaseJack, Queen, King func simpledescription ()-String {SwitchSelf { Case . Ace:return "Ace" Case . Jack:return "Jack" Case . Queen:return "Queen" Case . King:return "King" default: returnString (Self.rawvalue)}}}
Let ace = Rank. Ace
Let acerawvalue = ace. RawValue
Use rawValue to convert between raw (raw) values and enumeration values:
if 3 ) { = convertedrank.simpledescription ()}
Note the value of the member in the enumeration (member value) is the actual value (actual value), and the original (raw value) is not necessarily associated.
The member value of an enumeration is an actual value and is not an alternative expression of the original value. In fact, if the original value doesn't make sense, you don't need to set
enumSuit { CaseSpades, Hearts, Diamonds, Clubs func simpledescription ()-String {SwitchSelf { Case . Spades:return "Spades" Case . Hearts:return "Hearts" Case . Diamonds:return "Diamonds" Case . Clubs:return "Clubs"}}}let Hearts=Suit.heartslet heartsdescription= Hearts.simpledescription ()
In addition to associating a method, an enumeration also supports associating values on its members, and different members of the same enumeration can have different associated values:
enumServerresponse { CaseResult (String, String) CaseError (String)}let success= Serverresponse.result ("10:00am-6:00pm","8:09 pm") Let failure= Serverresponse.error ("Out of cheese.")SwitchSuccess { CaseLet . Result (Sunrise, Sunset): Let Serverresponse="Sunrise are at \ (Sunrise) and sunset are at \ (sunset)." CaseLet . Error (Error): Let Serverresponse="Failure ... \ (error)"}
2. Structural body
Swift uses the struct keyword to create the struct body. Structs and methods support the attributes of these classes. The biggest difference between structs and classes is that an instance of a struct is passed by value (passed by value), whereas an instance of a class is passed by reference (passed by reference).
struct Card { var rank:rank var suit:suit - String { return' The \ (Rank.simpledescription ()) of \ (Suit.simpledescription ())" == Threeofspades.simpledescription ()
Swift learns 4---enumerations and structs