The Enum Basics
Let’s Review
- Basic Enumerations
- Enumerations that have Raw Values
- Enumerations that have Associated Values
Create an enum called . It contains 4 cases.
You define multiple cases in a single line
enum Planet {
case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune
}
To initialize, you choose one of the cases.
let earth = Planet.earth // init
You may run through a switch
statement to identify the enum
type.
switch earth {
case .earth:
default:
print("Not a safe place for me")
}
// "Mostly safe"
Int
Float
String
Bool
Raw Value: String
enum Days: Int {
case mon, tue, wed, thu, fri = 10, sat, sun
}
let myDay = Days.fri.rawValue
print(myDay) // 10
Initialization from Raw Value
You may create an enum object using a raw value. it may fail. Therefore, the returned object may be nil
.
let possibleeDay = Days(rawValue: 10) // returns optional
print(possibleeDay!)
You may combine with a switch
statement.
if let someDay = Days(rawValue: 3) {
switch someDay {
case .sat, .sun:
print("Weekends!!")
print("Weekdays!")
}
} else {
print("No such day exists")
}
Each case may contain value along with it.
Validation
Determine if the instance is Barcode.qrCode
using an else-if
statement. The process is similar to implicit unwrapping.
if case let Barcode.qrCode(value) = qrCode {
print("This is a qrcode")
}
You may capture the associated value of the instance, qrCode
using case let
. You’ve named the captured value as value
.
if case let Barcode.upc(numberSystem, manufacturer, product, check) = upcCode {
print("numbersystem:", numberSystem)
print("manufaturer:",manufacturer)
print("product:",product)
print("check:",check)
}
Instead of checking each enum object individually using an else-if
, you may use a switch
statement.
let code = upcCode
switch code {
case .upc(let numberSystem, let manufacturer, let product, let check):
print("UPC: \(numberSystem), \(manufacturer), \(product), \(check).")
case .qrCode(let productCode):
print("QR code: \(productCode).")
The code below is identical as above. It gives off zenness.
Source Code
You’ve reviewed the three types of enums in the Swift Programming Language. If you are not comfortable with any, make sure you review and watch this video multiple times to get used to the syntax. Upcoming lessons will get more complex.
In the following lesson, you will learn how to use Swift enums to type less but produce more using practical examples in iOS development.