Day 51 - 100 Days of Swift

2 minute read

Expanding Horizons

Day 51 is a day where you “expand your horizons”. That basically means you watch a couple of conference talks that Paul Hudson gave, one at dotSwift 2018 on Functional Swift and one at NSSpain 2018 on Teaching Swift at Scale. Here are my notes from watching the talks:

Functional Swift

Why use functional code?

  • it makes as many things immutable as possible.
  • it avoids state, you pass things in, you get things out
  • because of the first two, it is more testable
  • it is compose-able, you can chain smaller functions together in interesting and complex ways
  • it expresses your intent clearly, it makes you write what you want, rather than how you’re going to get it.

Quick wins – things you can start applying to your existing code base without breaking anything.

  • map() - transforms stuff. Can use it inside of your existing functions (where applicable)
  • compactMap() - transforms stuff, but unwraps optionals. Really helpful for working with failable initializers and avoiding optional optionals.
  • filter() - get all the elements that match whatever criteria you want.
  • first() - get the first element that matches whatever criteria you want
  • reduce(0, +) - sum all the elements in an array
  • Array.contains(where: String.contains) - get all the elements that are contained in a string.

Teaching Swift at Scale

What problems do people hit when they’re learning Swift?

  • People struggle to learn the basics (CoreData)
  • System problems
    • UserDefaults. Keychain (use a wrapper!)
    • Timers. Invalidate your timers. Add a little tolerance (doesn’t drift, never early). Use a wrapper. CADisplayLink to ensure you get the full time between frames.
    • Attributed Strings. Use a wrapper.
    • Concurrency. Try to simplify.
  • UI Problems
    • Videos. Use AVPlayerViewController
    • ImageViews. Loading remote content into image views (don’t!). Use a wrapper.
    • WebViews.
    • Auto Layout. Use a wrapper.
  • Swift
    • Strings. Strings. Strings. Use StaticString where possible.
    • Optionals. Get rid of optionals as much as possible. Write throwing functions instead of returning optionals. Use nil coalescing to provide default values. Use compactMap().
  • Change
    • It’s hard to keep up. Things change a lot. Often in ways that break things. Refactor when you can.
  • Architecture
    • Get crap out of your view controllers. Put UI stuff and animations in UIView subclasses. Put navigation in a coordinator.

My main take away from this talk was “Stop trying to write wrappers for things yourself”. There are already a bunch out there that are better designed and better tested. Just use them.