Swift enums, tricks

Paulo Henri
2 min readDec 2, 2021

Enumeration is one of the most powerful features of language Swift, let’s report some uses here:

Declare enum witth raw value:

enum Simple : Int{
case yes = 10
case no = 20
}

var enumCase = .yes
print(enumCase.rawValue)

Associatad value from cases:

enum Associate{
case yes(value : Int)
case no(value : String)
}

var enumCase = Associate.yes(value: 10)
if case let enumCase = 10 {
print(“ is value\(enumCase)”)
}

Enum multiple types in associate value:

enum Associate{
case yes(value : Int, key : String)
case no(value : String, another : String)
}

var enumCase = Associate.no(value: “10”, another: “asd”)
switch enumCase {
case .no(let value, let key):
print( value, key)
case .yes(let value, let another):
print( value, another)
}

Enum methods

enum Associate{
case yes(value : Int, key : String)
case no(value : String, another : String)

func soma()->Int{
return 1 + 1
}
}

var enumCase = Associate.no(value: “10”, another: “asd”)
print(enumCase.soma())

Enum value by Self type

enum Associate{
case yes(value : Int, key : String)
case no(value : String, another : String)

func estoyCierto()->Bool{
switch self {
case .yes:
return true
case
.no:
return false
}
}
}

Computed properties:

enum Associate{

case yes(value : Int, key : String)

case no(value : String, another : String)

var currentValueString : String {

switch self {

case .yes(let value, let key):

return “ \(value) \(key) “

case .no(let value, let another):

return “ \(value) \(another) “

}

}

}

var enumCase = Associate.no(value: “10”, another: “asd”)

print(enumCase.currentValueString)

--

--

Paulo Henri

mobile developer, IOT enthusiast and Scrum master