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

Clean Coding in Swift

Clean Coding in Swift

Styling tips and strategies to clean up your Swift code, with help from Erica Sadun's book.

Mark Wilkinson

April 18, 2018

More Decks by Mark Wilkinson

Other Decks in Programming


  1. The Swift Way clean coding

  2. You’re telling a story - Daniel Steinberg

  3. What’s in a good story? •Succinct Titles and Section Headers

    •Sentences that convey meaning. •Grouping those sentences into a thought, or a paragraph.
  4. Succinct Titles and Headers (or better method signatures)

  5. better methods sigs

  6. pop-quiz ?

  7. Not succinct

  8. None
  9. { braces and (parens) } 2 styles of bracing C

    style (K&R) and C# (Allman)
  10. { bracing alignments } C-K&R Style C#-Allman

  11. No right or wrong choice Apple and most Swift developers

    continue with the C-K&R style Stay consistent, don’t mix the 2
  12. Speaking of alignments

  13. Anyone miss this?

  14. Knock yourself out (still prefer obj-c alignment of colons, but

    oh well)
  15. Proper alignment helped readability in Objective-c and it continues to

    help in Swift
  16. Parentheses () Hugging is best Avoid

  17. Parentheses? () Avoid them when there’s only 1 condition to

    an if or else if
  18. Statements that convey meaning

  19. Convey the meaning don’t expect the reader to deduce

  20. Group sentences into thoughts, or paragraphs

  21. Collections: Sugar or Generics?

  22. •Prefer Collection ‘Sugar’ in initializing or identifying the collection type

    ([Any] vs Array<Any>) •Prefer Generic form if you need to specify where Sugar inference doesn’t work (Set<Any> for instance) •The community at large seems to prefer [AnyHashable:Any] over Dictionary<,>, so it is what it is.
  23. if let cascading

  24. f*n awesome block syntax

  25. None
  26. •Embrace the closure argument sugar, avoid param names when the

    types are inferred •Prefer however named arguments when the implementation inside the block is nontrivial •Only use $0 when the params are worthless •Put your single closure as the last parameter to a method to get the last argument styling Erica’s rules
  27. Recognition above Recall

  28. on guard

  29. More cleaning

  30. •Replace common and (overlooked) if statements and if let pyramids

    with early-fail guard statements •Put multiple guard conditions on their own lines, allows breakpointing each line, commenting out conditions etc. •Even better, break each condition into it’s own guard statement
  31. •The selling point of guard usage is early failure, and

    finding bugs during development •Pair guard with assertionFailures to find exceptions early •guard statements help reduce if-let pyramids •They let the logic in a method focus on what needs to be done instead of checking for missing/nil conditions. Use guard
  32. optional unwrapping •Erica recommends not adding ‘valid’ or ‘unwrapped’ to

    the variable that is now valid. •This creates a scenario where validResponse might have existed somewhere else and is re-purposed •I personally keep using this style so proceed with caution.
  33. clean repurpose unwrapping

  34. Use assertions • assertionFailures should be used in place of

    many NSLog and print statements. • You the developer need to find crashing conditions early not in QA • Go through every console log (NSLog, print) and replace error reporting or add to them with an assertFailure
  35. • A great place to use them is in fail

    early guard statements • They are of course stripped out for a release build (assuming you’re using different builds) • fail early and stop to solve failures early not at the last minute or in a bug ticket
  36. Ternaries, or please stop • Ternary statements are just cryptic

    if-else conditions. • They can get more complex, and do nothing other than force another developer to decrypt them. • Harder to debug with breakpoints • Just refactor them out to if-else or guard statements.
  37. Finalize and seal • By default you should finalize your

    classes • Final prevents subclassing, which is the source of endless problems in the OO world. • Tells another developer you had no intention for this class to be subclassed and overrode. • Lack of subclassing introduces better patterns like protocols and containment
  38. If you have to subclass Prefer the abstract class pattern

    But there is no abstract keyword in Swift
  39. Those pesky baseViewControllers • The most common subclass is the

    viewController • Usually have properties that they all need, and most commonly, error reporting and alert showing
  40. Move to a protocol with extensions

  41. • The ViewController is still only 1 subclass deep. •

    It now implements a useful protocol with extended behavior • Add new protocols with their own extensions for other specific behaviors • This prevents massive god-base-classes
  42. other developers Mark Wilkinson

  43. You’ll influence other developers, which in turn will influence more

    down the line
  44. Smell the roses, not the code, embrace your personal style

    - Erica Sadun