Friday, October 9, 2015

Enumeration and Structures in Swift

Enumerations and structures also has similar capabilities as of Classes in Swift. 

enum Rank: Int 
{
case Ace = 1
case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
case Jack, Queen, King
func simpleDescription() -> String 
{
switch self
{
case .Ace:
return “Ace”
case .Jack:
return “Jack”
case .Queen
return “Queen”
case .King
return “King”
default:
return String(self.rawValue)
}
}
}

let ace = Rank.Ace
let rawAceRawValue = ace.rawValue


we can use the init?(rawValue:) initializer to make an instance of an enumeration from a raw value. 

if(let convertedRank = Rank(rawValue:3))
{
let desc = convertedRank.simpleDescription()
}

The raw values are not really required because the members of an enumeration are actual values. 

struct is used to define a structure. 

struct Card 
{
  var rank:Rank
var suite : Suit
func simpleDescription() -> String 
{
return “suite has \(rank.simpleDescription())”
}
}

let structinit = Card (rank:.Three, suite:.Spades) 

References:


No comments:

Post a Comment