Last active
March 16, 2017 01:11
-
-
Save brennanMKE/eac6c797a387c3f4d1034812532e9d30 to your computer and use it in GitHub Desktop.
Swift: Enums and Pattern Matching
This file contains 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
// SwiftCurriculum: https://github.com/brennanMKE/SwiftCurriculum | |
// Blog Post: https://medium.com/swift-curriculum/swift-enums-and-pattern-matching-8da7286c1060 | |
// Swift Version: 3.0 | |
import Foundation | |
enum Filling { | |
case chocolate | |
case cream | |
case fruit | |
} | |
enum Donuts { | |
case sugar(count: Int) | |
case sprinkles(count: Int) | |
case chocolate(count: Int) | |
case jelly(count: Int, filling: Filling) | |
} | |
func eatDonuts(donuts: Donuts) { | |
switch donuts { | |
case let .sugar(count) where count < 5: | |
print("🍩 Sugar donuts are so good.") | |
case let .sugar(count) where count >= 5: | |
print("🍩 Sugar donuts are so good but let's not go crazy.") | |
case let .sugar(count) where count == 0: | |
print("🍩 Why no donuts?!") | |
case let .jelly(_, filling) where filling == .chocolate: | |
print("🍩 Chocolate filling is so good! Great with coffee. ☕️") | |
case let .jelly(count, _) where count > 0: | |
print("🍩 Donuts with filling which is not chocolate is not for me.") | |
case let .sprinkles(count) where count == 0: | |
print("Why no donuts?!") | |
case let .chocolate(count) where count == 0: | |
print("Why no donuts?!") | |
default: | |
print("Mmmm... donuts.") | |
} | |
} | |
eatDonuts(donuts: .sugar(count: 4)) | |
eatDonuts(donuts: .sugar(count: 7)) | |
eatDonuts(donuts: .sprinkles(count: 0)) | |
eatDonuts(donuts: .chocolate(count: 2)) | |
eatDonuts(donuts: .jelly(count: 1, filling: .chocolate)) | |
eatDonuts(donuts: .jelly(count: 1, filling: .cream)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment