Swift: Enum type

This entry is part 28 of 41 in the series Swift

An enum type is a special data type that enables for a variable to be a set of predefined constants.

The variable must be equal to one of the values that have been predefined for it.

Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.

enum Suit {
    
    case Spades, Hearts, Diamonds, Clubs
    
    func typeofCard() -> String {
        
        switch self {
            
        case .Spades:
            return "I am a spade"
        case .Hearts:
            return "I am a heart"
        case .Diamonds:
            return "I am a diamond"
        case .Clubs:
            return "I am a club"
        }
        
    }
    
    func color() -> String {
        
        switch self{
            
        case .Spades:
            return "my color is black"
        case .Clubs:
            return "my color is blue"
        case .Diamonds:
            return "my color is white"
        case .Hearts:
            return "my color is red"
        }
    }
}

let hearts: Suit = .Hearts
print("Suit is: \(Suit.Hearts)")

let card = hearts.typeofCard()
print("Card is: \(card)")

print("Color is: \(hearts.color())")

swift

Series Navigation<< Swift: Switch and default case
Swift: Saying hello with a closure >>

Leave a comment

Leave a Reply