Variables

Enumerations in Swift

Enumerations are used to group related values together. These values can either be raw or have associated values of primitive types (String, Int, etc.).


Syntax
//raw values
enum enumerationName {
    case value1, value2 //
}
//associative values
enum enumerationName2 {
    case valueName(valueType1, valueType2) //cases can contain multiple associative values
    case valueDefault = defaultValue //default raw values can be assigned as well
}

//assigning values for associative
var variable = enumerationName2.valueName(someValue1, someValue2)

//used in a switch statment
switch enumerationName {
    case .value1:
        //statements
}

switch enumerationName2 {
    case .valueName(let someValue1, let someValue2):
        //statements
    }
}

Notes

Raw values must be unique in declaration.


Example
enum DaysOfWeek {
    case Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
}

enum Date {
    case Day (Int)
    case Month (String)
    case Year (Int)
}

let day = Date.Day(5)
let month = Date.Month("July")
let year = Date.Year(2015)

< Sets   |   If Statement >

© 2019 SyntaxDB. All Rights Reserved.