Created
February 28, 2019 02:49
-
-
Save cyyeh/9801e4599b3796b54cb5b7964b99bff5 to your computer and use it in GitHub Desktop.
Swift Enumerations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| Referenced from Stanford CS193p | |
| #: important | |
| ##: very important | |
| Enumerations | |
| - Enumeration Syntax | |
| - Matching Enumeration Values with a Switch Statement | |
| - #Associated Values | |
| Reference: https://docs.swift.org/swift-book/LanguageGuide/Enumerations.html | |
| */ | |
| /* | |
| Enumeration Syntax | |
| */ | |
| enum CompassPoint { | |
| case north | |
| case south | |
| case east | |
| case west | |
| } | |
| enum Planet { | |
| case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune | |
| } | |
| var directionToHead = CompassPoint.west | |
| directionToHead = .east | |
| /* | |
| Matching Enumeration Values with a Switch Statement | |
| */ | |
| directionToHead = .south | |
| switch directionToHead { | |
| case .north: | |
| print("Lots of planets have a north") | |
| case .south: | |
| print("Watch out for penguins") | |
| case .east: | |
| print("Where the sun rises") | |
| case .west: | |
| print("Where the skies are blue") | |
| } | |
| // Prints "Watch out for penguins" | |
| let somePlanet = Planet.earth | |
| switch somePlanet { | |
| case .earth: | |
| print("Mostly harmless") | |
| default: | |
| print("Not a safe place for humans") | |
| } | |
| // Prints "Mostly harmless" | |
| /* | |
| #Associated Values | |
| */ | |
| enum Barcode { | |
| case upc(Int, Int, Int, Int) | |
| case qrCode(String) | |
| } | |
| var productBarcode = Barcode.upc(8, 85909, 51226, 3) | |
| productBarcode = .qrCode("ABCDEFGHIJKLMNOP") | |
| switch productBarcode { | |
| case .upc(let numberSystem, let manufacturer, let product, let check): | |
| print("UPC: \(numberSystem), \(manufacturer), \(product), \(check).") | |
| case .qrCode(let productCode): | |
| print("QR code: \(productCode).") | |
| } | |
| // Prints "QR code: ABCDEFGHIJKLMNOP. | |
| switch productBarcode { | |
| case let .upc(numberSystem, manufacturer, product, check): | |
| print("UPC : \(numberSystem), \(manufacturer), \(product), \(check).") | |
| case let .qrCode(productCode): | |
| print("QR code: \(productCode).") | |
| } | |
| // Prints "QR code: ABCDEFGHIJKLMNOP." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment