Enum or Enumerations are a special data types that enable us to group related types together and use them in a type-safe manner. enum in swift is not limited to an integer value as they are in another language, such as C or Java. enum in swift can have a string, character, integer, floating-point and much more type and define its actual value (raw value)
Defining enum in swift
enum Direction {
case East
case West
case North
case South
}
There is a shorter version also that lets us define multiple members in a single line separated by commas.
enum Direction {
case East, West, North, South
}
Using enum
switch windDirection {
case .East: print("East")
case .West: print("West")
case .North: print("North")
case .South: print("South")
default: ()
}
if windDirection == .East {
print("East")
}
Value Type and Raw Value Enum
Enum can have Int, String, Double, Bool as a value type. For String and Int types, you can even omit the values and the Swift compiler will do the right thing:
// Mapping to Integer
enum Movement: Int {
case Left = 0
case Right = 1
case Top = 2
case Bottom = 3
}
// You can also map to strings
enum MacVersion: String {
case MacOS8
case MacOS9 = "Mavrick"
case MacOS10 = "Yosemite"
case MacOS11 = "El Capitan"
case MacOS12 = "Sierra"
}
// Or to floating point (also note the fancy unicode in enum cases)
enum Constants: Double {
case π = 3.14159
case e = 2.71828
case φ = 1.61803398874
case λ = 1.30357
}
Accessing and initializing enum
Enum values can be accessed and initialized by rawValue property. While initializing enum with rawValue, it is of type optional as not all value passed have mapped to enum member.
let move = Movement(rawValue: 1) //Left
let version = MacVersion(rawValue: "Mavrick") //MacOS9
let ver = MacVersion(rawValue: "Leopard") // nil
print(MacVersion.MacOS10.rawValue) // Mavrick
print(MacVersion.MacOS8.rawValue) // MacOS8
Associated Values
Swift enum can also have associated values which allow us to store additional information along with member values. This additional information can vary between the enum member.
enum Product {
case Book(cost: Double, pages: Int, author:String)
case Mobile(cost: Double, osVersion: String)
}
let swiftBook = Product.Book(cost: 220.0, pages: 500, author: "twanabashu")
let iPhone = Product.Mobile(cost: 98000, osVersion: "10")
switch swiftBook {
case .Book(let cost, let pages, let author):
print("cost:\(cost) pages: \(pages) author: \(author)")
case .Mobile(let cost, let osVersion):
print("cost: \(cost)osVersion:\(osVersion)")
}
Method and Properties
enum in swift can have method and properties like structure and class
enum Device {
case iPad, iPhone, AppleTV, AppleWatch
var year: Int {
switch self {
case .iPhone: return 2007
case .iPad: return 2010
default:()
}
return 0
}
static func from(term: String) -> Device? {
if term == "iWatch" {
return .AppleWatch
}
return nil
}
func introduced() -> String {
switch self {
case .AppleTV: return "\(self) was introduced 2006"
case .iPhone: return "\(self) was introduced 2007"
case .iPad: return "\(self) was introduced 2010"
case .AppleWatch: return "\(self) was introduced 2014"
}
}
}
print (Device.iPhone.introduced()) //iPhone was introduced 2007
print (Device.iPhone.year) //2007
print(Device.from(term: "iWatch")!) //AppleWatch
Mutating Methods
Methods can be declared mutating. They’re then allowed to change the case of the underlying self-parameter.
enum GameLevel {
case Level1, Level2, Level3
mutating func upgrade(){
switch self {
case .Level1:
self = .Level2
case .Level2:
self = .Level3
case .Level3:
self = .Level3
default:()
}
}
}
var level = GameLevel.Level1 // Level1
level.upgrade() //Level2
Generic Enums
Enums can also be defined over generic parameters. You’d use them to adapt the associated values of an enum.
struct Dog {
var name: String
}
struct Human {
var name: String
}
enum Avatar<T, U> {
case Dog(T)
case Human(U)
}
let dog = Dog(name: "tiger")
let human = Human(name: "ravi")
let mammal = Avatar<Dog, Human>.Dog(dog)
switch mammal {
case .Dog(let dog): print(dog.name)
case .Human(let human): print(human.name)
default:()
}
enum as Identifiers and constants
Enums can be used to map reuse identifiers or storyboard identifiers. Similarly, enum can be used to hold constant. In normal ways, you cannot have more than one parameter with the same name in one application, but with enum we can achieve this and this will make lot easier to manage constant in application
enum Constant {
enum Identifier {
static let identifier1 = "identifier1"
static let identifier2 = "identifier2"
static let identifier3 = "identifier3"
}
enum Production {
static let baseURL = "http://production.com"
}
enum Uat {
static let baseURL = "http://uat.com"
}
}
let viewid = Constant.Identifier.identifier1
#if DEBUG
let baseUrl = Constant.Uat.baseURL
#else
let baseUrl = Constant.Production.baseURL
#endif
Looking at the advance use of enum, it is very similar to a struct in swift. It can have a parameter, methods. One should know the difference between enum and swift here and when to use.
- enums are initialized by one of a finite number of cases, are completely defined by their case, and should always be valid instances of that case when instantiated
- structs should be used when there is not a finite number of valid instances (e.g. enum cases) and the struct also does not form a complete definition of an object, but rather an attribute of an object
Webmentions
list of reputable canadian pharmacies https://ecoutegli.bandcamp.com/track/pharmacies-shipping-to-usa
Regards. Terrific stuff.
trust pharmacy canada https://solorider.com/forums/users/canadian-pharmaceuticals/
You revealed that really well!
pharmacy https://bitcoinblack.net/community/prescription-drugs-from-canada/info/
Excellent info. Many thanks.
canadian rx https://rabbitroom.com/members/canadianpharmaceuticalsonlinewithnoprescription/profile/
Beneficial knowledge. Thank you!
canada pharmacy https://the-dots.com/projects/drugstore-online-shopping-889086/
This is nicely put. !
online canadian pharmacies https://cialispharmacy.cgsociety.org/profile
Regards. I appreciate this!
canadian online pharmacies https://haikudeck.com/presentations/cheapprescriptiondrugs
Awesome material. Many thanks!
canada pharmacy https://www.gamespace.com/members/canadianprescriptionsonline/
Seriously all kinds of awesome info.
no 1 canadian pharcharmy online http://canadianpharmaceuticalsonlinee.iwopop.com/
Perfectly spoken certainly! .
canadian pharcharmy online https://linktr.ee/canadianpharmaceuticalsonlineu
You actually expressed it effectively!
canada pharmacies online prescriptions https://halttancentnin.livejournal.com/301.html
Excellent posts. Thanks a lot!
canada drug pharmacy https://canadianpharmaceuticalsonline.myjournal.jp/archives/18054504.html
Really tons of beneficial info.
canadian pharcharmy online https://canadianpharmaceuticalsonline.publog.jp/archives/16846649.html
Really a lot of beneficial tips.
erectile dysfunction medications https://challonge.com/afersparun
Thanks a lot, Helpful information!
canada pharmacies https://rentry.co/canadianpharmaceuticalsonline
You have made your point!
canadian pharmacies mail order https://jemi.so/canadian-pharmacies-shipping-to-usa
With thanks, Loads of facts!
highest rated canadian pharmacies https://www.podcasts.com/canadian-pharmacies-shipping-to-usa
You reported that fantastically.
buy ivermectin online https://telegra.ph/Order-Stromectol-over-the-counter-10-29
Reliable posts. Many thanks!
stromectol doses https://buystromectol.livejournal.com/421.html
You explained that well.
facts stromectol https://orderstromectoloverthecounter.mystrikingly.com/
Wonderful forum posts. Kudos.
generic stromectol https://aleserme.estranky.sk/clanky/stromectol-espana.html
Useful advice. Thank you.
stromectol buy https://pinshape.com/users/2491694-buy-stromectol-fitndance
With thanks. Loads of material.
stromectol treatment scabies https://aoc.stamford.edu/profile/cliclecnotes/
Good info, Kudos!
canadian drug https://feeds.feedburner.com/bing/stromectolnoprescription
Truly loads of awesome tips.
canadian rx https://feeds.feedburner.com/bing/Canadian-pharmaceuticals-online
Appreciate it! A good amount of data!
best canadian mail order pharmacies https://www.giantbomb.com/profile/canadapharmacy/blog/canadian-pharmaceuticals-online/265652/
Cheers, Ample information.
stromectol in india https://sanangelolive.com/members/girsagerea
Nicely put. Appreciate it.
trust pharmacy canada https://network.myscrs.org/profile/422020/0
Thanks a lot, Wonderful information.
canada pharmacies online https://moaamein.nacda.com/profile/422018/0
You said it very well..
stromectol canada https://inflavnena.zombeek.cz/
Thank you! I like it.
ivermectin tablets https://order-stromectol-over-the-counter.estranky.cz/clanky/order-stromectol-over-the-counter.html
You expressed it fantastically.
canada drug https://bursuppsligme.bandcamp.com/releases
Good data. Regards.
stromectol purchase https://aoc.stamford.edu/profile/Stromectol/
Very good knowledge. Appreciate it!
legitimate canadian mail order pharmacies https://canadajobscenter.com/author/canadianpharmaceuticalsonline/
Nicely put. Appreciate it!
prescriptions from canada without https://www.scoop.it/topic/canadian-pharmaceuticals-online
Thanks a lot, I like it.
trust pharmacy canada https://pinshape.com/users/2441403-canadian-pharmaceuticals-online
With thanks! Lots of knowledge.
online prescriptions without a doctor https://challonge.com/en/canadianpharmaciesshippingtousa
Thanks! An abundance of advice!
online prescriptions without a doctor https://buyviagraonline.nethouse.ru/
Terrific content. Thank you.
online prescriptions without a doctor https://buyviagraonline.fo.team/
Many thanks, Numerous postings.
online prescriptions without a doctor https://buyviagraonline.flazio.com/
Nicely put. Thanks!
prescription drugs without prior prescription https://linktr.ee/onlinepharmacies
You expressed that wonderfully!
pharmacy https://kawers.micro.blog/
Awesome information. Cheers!
northwest pharmacies https://hub.docker.com/r/pharmacies/online
Helpful material. Thanks!
medication without a doctors prescription https://site273035107.fo.team/
You’ve made your point pretty clearly..
Northwest Pharmacy https://womed7.wixsite.com/pharmacy-online/post/new-ideas-into-canada-pharmacies-never-before-revealed
Position nicely used!!
canadian discount pharmacies https://kewertyn.wordpress.com/2022/04/27/expect-more-virtual-house-calls-out-of-your-doctor-thanks-to-telehealth-revolution/
You actually expressed this wonderfully!
online prescriptions without a doctor https://ghswed.wordpress.com/2022/04/27/he-final-word-information-to-online-pharmacies/
Kudos, I enjoy it.
online canadian pharmacies https://site128620615.fo.team/
Great forum posts. With thanks.
medication without a doctors prescription https://seketu.gonevis.com/high-10-tips-with-order-medicine-online-1/
Superb data. Thanks a lot!
legitimate canadian mail order pharmacies https://viagravonline.com/
You made your position extremely well!.
canada drug http://rennchonddust.webcindario.com
You actually said that perfectly.
canadian pharmacies that are legit http://flordylua.webcindario.com
Effectively spoken indeed! !
canadian pharmacies that are legit http://formlawhols.webcindario.com
You have made your stand very nicely!.
online canadian pharmacies http://laufreerax.webcindario.com
Appreciate it. An abundance of info!
pharmacy http://swermapi.webcindario.com
Seriously many of excellent material.
best canadian mail order pharmacies http://detrimo.webcindario.com
Thanks! A good amount of knowledge!
legitimate canadian mail order pharmacies http://ginnfatert.webcindario.com
Regards! A good amount of stuff.
canada drugs http://wormiki.webcindario.com
Thank you, A good amount of posts!
prescription drugs without prior prescription http://withoutadoctor.viagraiy.com/
Very good tips. With thanks.
prescription drugs without prior prescription http://canadianorderpharmacy.com/
Cheers. Quite a lot of tips!