Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Stupid Enum Tricks in Swift and Kotlin - We Are Developers, Vienna, Austria, May 2018

Stupid Enum Tricks in Swift and Kotlin - We Are Developers, Vienna, Austria, May 2018

Enums in Swift and enum classes in Kotlin are extremely powerful ways to deal with a known set of possible values. Learn how to use these tools to help you cleaner, safer code, and how to push the boundaries of what's possible with enums.

Ellen Shapiro

May 16, 2018
Tweet

More Decks by Ellen Shapiro

Other Decks in Technology

Transcript

  1. STUPID ENUM TRICKS IN SWIFT AND KOTLIN WE ARE DEVELOPERS

    | VIENNA, AUSTRIA | MAY 2018 BAKKENBAECK.COM | JUSTHUM.COM | DESIGNATEDNERD.COM BY ELLEN SHAPIRO | @DESIGNATEDNERD
  2. GIF

  3. GIF

  4. SWIFT enum ColorName: String { case red case orange case

    yellow case green case blue case violet }
  5. SWIFT func colorForName(_ name: String) -> UIColor? { switch name

    { case ColorName.red.rawValue: return UIColor.red case ColorName.orange.rawValue: return UIColor.orange // same for other ColorName cases default: return nil }
  6. SWIFT STANDARD LIBRARY public enum ComparisonResult : Int { case

    orderedAscending case orderedSame case orderedDescending }
  7. SWIFT var currentColor: TrafficLightColor = .red switch currentColor { case

    .red: print("STOP RIGHT THERE") case .yellow: print("Whoa, slow down there, buddy.") case .green: print("Go, go, go!") }
  8. SWIFT var currentColor: TrafficLightColor = .red switch currentColor { case

    .red: print("STOP RIGHT THERE") case .green: print("Go, go, go!") // Error: Unhandled case! }
  9. SWIFT var currentColor: TrafficLightColor = .red switch currentColor { case

    .red: print("STOP RIGHT THERE") case .yellow, .green: print("Go, go, go!") }
  10. KOTLIN var currentColor = TrafficLightColor.Red when (currentColor) { TrafficLightColor.Red ->

    println("STOP RIGHT THERE") TrafficLightColor.Yellow -> println("Whoa, slow down there, buddy.") TrafficLightColor.Green -> println("Go, go, go!") }
  11. KOTLIN Instance Gets You Example instance.name String value of case's

    written name Days.THURSDAY.name is "THURSDAY", Days.Thursday.name is "Thursday" instance.ordinal Index of case in list of cases
  12. KOTLIN Type Gets You Type.valueOf(string: String) Enum value of string,

    or null Type.values() Generated list of all values in the enum class
  13. SWIFT enum SettingsSection: Int { case profile // 0 case

    contact // 1 case legalese // 2 case logout // 3 }
  14. SWIFT enum SettingsSection: Int { case profile // 0 case

    legalese // 1 case contact // 2 case logout // 3 }
  15. SWIFT enum JSONKey: String { case user_name case email_address case

    latitude = "lat" case longitude = "long" }
  16. SWIFT Codable class User: Codable { let userName: String let

    email: String let latitude: Double let longitude: Double enum CodingKeys: String, CodingKey { case userName = "user_name" case email = "email_address" case latitude = "lat" case longitude = "long" } }
  17. SWIFT enum SettingsSection: Int, CaseIterable { case profile case legalese

    case contact case logout } // Automatically generated: static var allCases: [SettingsSection]
  18. SWIFT func numberOfSectionsInTableView(_ tableView: UITableView) -> Int { return SettingsSection.allCases.count

    } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String { let section = SettingsSection.allCases[section] return section.localizedTitle }
  19. SWIFT enum LandingScreenButton { case signIn case signUp case viewTerms

    var localizedTitle: String { switch self { case .signIn: return NSLocalizedString("Sign In", "Sign in button title") case .signUp: return NSLocalizedString("Sign Up", "Sign up button title") case .viewTerms: return NSLocalizedString("View Terms & Conditions", "Title for button to view legalese") } }
  20. SWIFT public enum LandingScreenButton { case signIn case signUp case

    viewTerms public var localizedTitle: String { switch self { case .signIn: return NSLocalizedString("Sign In", "Sign in button title") case .signUp: return NSLocalizedString("Sign Up", "Sign up button title") case .viewTerms: return NSLocalizedString("View Terms & Conditions", "Title for button to view legalese") } }
  21. SWIFT / IOS: AFTER public enum Asset: String { case

    cinnamon_rolls case innocent case no case snack case window var image: UIImage { return UIImage(named: self.rawValue)! } }
  22. SWIFT / IOS: TESTS! func testAllAssetsAreThere() { XCTAssertNotNil(UIImage(named: Asset.cinnamon_rolls.rawValue)) XCTAssertNotNil(UIImage(named:

    Asset.cinnamon_rolls.rawValue)) XCTAssertNotNil(UIImage(named: Asset.cinnamon_rolls.rawValue)) XCTAssertNotNil(UIImage(named: Asset.cinnamon_rolls.rawValue)) XCTAssertNotNil(UIImage(named: Asset.cinnamon_rolls.rawValue)) }
  23. SWIFT / IOS: TESTS! func testAllAssetsAreThere() { XCTAssertNotNil(UIImage(named: Asset.cinnamon_rolls.rawValue)) XCTAssertNotNil(UIImage(named:

    Asset.cinnamon_rolls.rawValue)) XCTAssertNotNil(UIImage(named: Asset.cinnamon_rolls.rawValue)) XCTAssertNotNil(UIImage(named: Asset.cinnamon_rolls.rawValue)) XCTAssertNotNil(UIImage(named: Asset.cinnamon_rolls.rawValue)) } !
  24. SWIFT / IOS: TESTS! func testAllAssetsAreThere() { for asset in

    Asset.allCases { XCTassertNotNil(UIImage(named: asset.rawValue), "Image for \(asset.rawValue) was nil!") } }
  25. SWIFT / IOS: TESTS! func testAllAssetsAreThere() { for asset in

    Asset.allCases { XCTassertNotNil(UIImage(named: asset.rawValue), "Image for \(asset.rawValue) was nil!") } } !!!!!!!
  26. SWIFT: BEFORE @IBAction private func signIn() { guard self.validates() else

    { return } performSegue(withIdentifier: "toCatsLoggedIn", sender: nil) }
  27. SWIFT: THE ENUM enum MainStoryboardSegue: String { case toSignIn case

    toSignUp case toTerms case toCats case toCatsLoggedIn }
  28. SWIFT: THE PROTOCOL WITH A GENERIC EXTENSION FUNCTION protocol SeguePerforming

    { var rawValue: String { get } } extension UIViewController { func perform<T: SeguePerforming>(segue: T, sender: Any? = nil) { performSegue(withIdentifier: segue.rawValue, sender: sender) } }
  29. SWIFT: THE ENUM, REVISED enum MainStoryboardSegue: String, SeguePerforming { case

    toSignIn case toSignUp case toTerms case toCats case toCatsLoggedIn }
  30. SWIFT: AFTER @IBAction private func signIn() { guard self.validates() else

    { return } self.perform(MainStoryboardSegue.toCats) }
  31. SWIFT enum DownloadState { case notStarted, case downloading(let progress: Float)

    case success(let data: Data) case error(let error: Error?) }
  32. KOTLIN sealed class DownloadStateWithInfo { class NotStarted: DownloadStateWithInfo() class Downloading(val

    progress: Float): DownloadStateWithInfo() class Succeeded(val data: ByteArray): DownloadStateWithInfo() }
  33. KOTLIN sealed class DownloadStateWithInfo { class NotStarted: DownloadStateWithInfo() class Downloading(val

    progress: Float): DownloadStateWithInfo() class Succeeded(val data: ByteArray): DownloadStateWithInfo() class Failed(val error: Error): DownloadStateWithInfo() }
  34. KOTLIN inline fun <reified T: Enum<T>> T.next(): T { val

    currentIndex = this.ordinal val nextIndex = currentIndex + 1 val allValues = enumValues<T>() return if (nextIndex >= allValues.size) { allValues[0] } else { allValues[nextIndex] } }
  35. KOTLIN inline fun <reified T: Enum<T>> T.next(): T { //

    val currentIndex = this.ordinal // val nextIndex = currentIndex + 1 // val allValues = enumValues<T>() // return if (nextIndex >= allValues.size) { // allValues[0] // } else { // allValues[nextIndex] // } }
  36. KOTLIN inline fun <reified T: Enum<T>> T.next(): T { //

    val currentIndex = this.ordinal // val nextIndex = currentIndex + 1 val allValues = enumValues<T>() // return if (nextIndex >= allValues.size) { // allValues[0] // } else { // allValues[nextIndex] // } }
  37. KOTLIN inline fun <reified T: Enum<T>> T.next(): T { //

    val currentIndex = this.ordinal // val nextIndex = currentIndex + 1 // val allValues = enumValues<T>() return if (nextIndex >= allValues.size) { allValues[0] } else { allValues[nextIndex] } }
  38. KOTLIN sealed class DownloadStateWithInfo { class NotStarted: DownloadStateWithInfo() class Downloading(val

    progress: Float): DownloadStateWithInfo() class Succeeded(val data: ByteArray): DownloadStateWithInfo() class Failed(val error: Error): DownloadStateWithInfo() }
  39. SWIFT: GOOD enum LandingScreenButton { // Stuff we saw before

    var localizedTitle: String { switch self { case .signIn: return NSLocalizedString("Sign In", "Sign in button title") case .signUp: return NSLocalizedString("Sign Up", "Sign up button title") case .viewTerms: return NSLocalizedString("View Terms & Conditions", "Title for button to view legalese") } }
  40. SWIFT: OVER THE TOP enum LandingScreenButton { // Stuff we

    saw before func handleClick(in viewController: UIViewController) { switch self { case .signIn: viewController.navigationController? .pushViewController(SignInViewController(), animated: true) case .signUp: viewController.navigationController? .pushViewController(RegistrationViewController(), animated: true) case .viewTerms: viewController.present(LegaleseViewController(), animated: true) } } }
  41. OBLIGATORY SUMMARY SLIDE > Enums are a great way to

    represent distinct state > Limit your cases, limit your bugs
  42. OBLIGATORY SUMMARY SLIDE > Enums are a great way to

    represent distinct state > Limit your cases, limit your bugs > Value determined by the current case -> computed var
  43. OBLIGATORY SUMMARY SLIDE > Enums are a great way to

    represent distinct state > Limit your cases, limit your bugs > Value determined by the current case -> computed var > Generated enums help reduce stringly-typed code
  44. OBLIGATORY SUMMARY SLIDE > Enums are a great way to

    represent distinct state > Limit your cases, limit your bugs > Value determined by the current case -> computed var > Generated enums help reduce stringly-typed code > Don't forget about separation of concerns
  45. LINKS! > The Swift book's section on Enums: https://developer.apple.com/library/ content/documentation/Swift/Conceptual/

    Swift_Programming_Language/ Enumerations.html > Kotlin Enum Class documentation: https://kotlinlang.org/docs/reference/ enum-classes.html