Swift Style An Opinionated Guide to an Opinionated Language by Erica Sadun Version: P1.0 (March 2017) Copyright © 2017 The Pragmatic Programmers, LLC This book is licensed to the individual who purchased it We don't copy-protect it because that would limit your ability to use it for your own purposes Please don't break this trust—you can use this across all of your devices but please not share this copy with other members of your team, with friends, or via file sharing services Thanks Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks Where those designations appear in this book, and The Pragmatic Programmers, LLC was aware of a trademark claim, the designations have been printed in initial capital letters or in all capitals The Pragmatic Starter Kit, The Pragmatic Programmer, Pragmatic Programming, Pragmatic Bookshelf and the linking g device are trademarks of The Pragmatic Programmers, LLC Every precaution was taken in the preparation of this book However, the publisher assumes no responsibility for errors or omissions, or for damages that may result from the use of information (including program listings) contained herein About the Pragmatic Bookshelf The Pragmatic Bookshelf is an agile publishing company We’re here because we want to improve the lives of developers We this by creating timely, practical titles, written by programmers for programmers Our Pragmatic courses, workshops, and other products can help you and your team create better software and have more fun For more information, as well as the latest Pragmatic titles, please visit us at http://pragprog.com Our ebooks not contain any Digital Restrictions Management, and have always been DRM-free We pioneered the beta book concept, where you can purchase and read a book while it’s still being written, and provide feedback to the author to help make a better book for everyone Free resources for all purchasers include source code downloads (if applicable), errata and discussion forums, all available on the book's home page at pragprog.com We’re here to make your life easier New Book Announcements Want to keep up on our latest titles and announcements, and occasional special offers? Just create an account on pragprog.com (an email address and a password is all it takes) and select the checkbox to receive newsletters You can also follow us on twitter as @pragprog About Ebook Formats If you buy directly from pragprog.com, you get ebooks in all available formats for one price You can synch your ebooks amongst all your devices (including iPhone/iPad, Android, laptops, etc.) via Dropbox You get free updates for the life of the edition And, of course, you can always come back and re-download your books when needed Ebooks bought from the Amazon Kindle store are subject to Amazon's polices Limitations in Amazon's file format may cause ebooks to display differently on different devices For more information, please see our FAQ at pragprog.com/frequently-asked-questions/ebooks To learn more about this book and access the free resources, go to https://pragprog.com/book/esswift, the book's homepage Thanks for your continued support, Andy Hunt The Pragmatic Programmers The team that produced this book includes: Andy Hunt (Publisher), Janet Furlow (VP of Operations), Susannah Davidson Pfalzer (Executive Editor), Brian MacDonald (Development Editor), Potomac Indexing, LLC (Indexing), Linda Recktenwald (Copy Editor), Gilson Graphics (Layout) For customer support, please contact support@pragprog.com For international rights, please contact rights@pragprog.com This book is dedicated to the Swift community both inside and outside Apple Table of Contents Welcome to Swift Style How This Book Got Here Your Code Doesn’t Smell What’s in This Book Contributing to This Book Online Resources Ready to Get Going? Credits Thanks Structure Your Code for Readability Taking Control of Swift Structure Understanding Swift Semicolons Styling Colinear Braces Hugging Parentheses Wrapping Argument Lists Coaligning Assignments Improving Closure Hygiene Choosing Trailing Closures Laying Out Partial Application Laying Out Complex Guard Statements Laying Out Ternaries Binary Conditionals Laying Out Long Collections Weighing Late Property Declaration Wrapping Up Adopt Conventional Styling Adopting Conventional Spacing Mandating Maximum Line Widths Selecting Colon Styles Placing Attributes Formatting Number Literals Balancing Literals and Types Constructing Collections with Literals Optional Sugar Mitigating Optional Constipation Converting to Tuples Considering Comma-First Styles Wrapping Up Establish Preferred Practices Testing Assumptions Choosing Optionals Converting Collection Lookup to Optionals Casting Conditionally Chaining Calls Moving from Thrown Errors to Optionals Unwrapping Variables Mapping in Condition Clauses Iterating Collections of Optionals Working with Optional Collections Choosing Result Types Adding Lazy Evaluation Selecting Sequences and Strides Looping Indexing and Enumerating Collections Switch Statements Declaring Number Constants and Variables Implementing Getters and Setters Returning Void Grouping Initializers Using Call Site Inferencing Evaluating Case-Binding Syntax Using If/Guard-Case Choosing Capture Modifiers Other Practices Wrapping Up Design the Right APIs Adopting Access Control Avoiding Global Symbols Nesting Functions Nesting Types Designing Singletons Adding Custom Operators Naming Generic Parameters Naming Symbols Plurality Choosing Label Names Initializers Convenience Initializers Naming Methods and Functions Tips for Naming Mutating Variations Computed Properties vs Methods Adding Defaults Protocols Generic Beautification Adding Typealiases Choosing Value vs Reference Types Writing Good Errors Wrapping Up Look to the Past and the Future Reconciling Past You vs Future You Documenting in Real Time Adding Structured Markup Commenting Well Organizing with Bookmarks Improving Code Descriptions Avoiding Clever Wrapping Up Good Code Copyright © 2017, The Pragmatic Bookshelf (label: String?, value: Any) -> String in guard let label = label else { return "\(value)" } return value is String ? "\(label): \"\(value)\"" : "\(label): \(value)" }) if chunks.isEmpty { return "\(instance)" } let chunksString = chunks.joined(separator: ", ") return "\(mirror.subjectType)(\(chunksString))" } /// Conforms to CustomStringConvertible public var description: String { return DefaultDescription(instance: self) } } extension Class: DefaultReflectable {} print(Class()) // Class(a: 1, b: "two") Although this topic may seem out of scope at first glance, establishing robust representations for your debugging output plays an essential role in good Swift style Prefer to enhance the way your code supports state presentation, inspection, and exploration Support type descriptions with custom string output Support debugger output with custom mirrors Reflect the semantics as well as the underlying structure of the types you create This extra information is invaluable for debugging Avoiding Clever No one likes clever code or clever comments—not even the person who was so pleased when she first wrote that material As Brian Kernighan wrote in The Elements of Programming Style, “Everyone knows that debugging is twice as hard as writing a program in the first place So if you’re as clever as you can be when you write it, how will you ever debug it?” Developer Justin Etheredge wrote a wonderful essay about this called “Don’t be clever.”[83] He writes that simplicity and understandability trump cleverness Good code qualities include loose coupling, testability, exception handling, and generally good design It’s better, in his opinion, to be a good software engineer than to win the International Obfuscated C Code Contest When writing code, emphasize the practical over being showy Simple, durable, and reliable code should be your primary goal “Programming is not like being in the CIA, you don’t get credit for being sneaky.”—Steve McConnell (Code Complete, Microsoft Press, 2004) Saying, “I’m a one-person shop so I don’t have to document” doesn’t take into account the fact that future you is a primary client of both your code and your comments Minimize humor because humor travels poorly A symbol or comment that’s meant to be self-deprecating may misfire at some future point Use symbol names and comment phrasing that does not insult your cubical mate, your manager, or the persons who developed the API you’re struggling with Use whitespace liberally to avoid “blocky info-dump of doom” scenarios Let carefully placed line breaks chunk information into more manageable concepts Respect the time of the person reading your code Keep your comments short, to the point, and valuable to the reader Use a linter Linters more than remove trailing whitespace on lines and in files They allow you to automate common scanning tasks so you can focus your energies on writing and debugging code, not proofing its structure The SwiftLint[84] project is the most prevalent community linter at this time Wrapping Up You’ve now read about ways to future-proof your code No matter how hard you try to stay current on your codebase, time and memory work against you The realities of human cognition mean that investing time in documenting, structuring, and refining code will pay off as your code ages and matures and its recency diminishes You’ve discovered how Swift implements a custom markup system to support inline documentation and how to mix and match doc markup with traditional comment systems You’ve read about bookmark organization and how to improve the quality of words that make up your code You’ve also considered how clever code can weigh down a project by limiting its maintainability and flexibility Now that you’ve spent time reading about designing for resilience, turn your attention to the qualities that make code great This book concludes with a short meditation on good code Read on for a few inspiring words Footnotes [73] http://commonmark.org [74] https://swift.org [75] https://swift.org/documentation/api-design-guidelines/ [76] https://developer.apple.com/library/content/documentation/Xcode/Reference/xcode_markup_formatting_ref/ [77] https://itunes.apple.com/us/book/swift-documentation-markup/id1049010423?mt=11 [78] https://leanpub.com/swiftdocumentationmarkup [79] https://github.com/realm/jazzy [80] http://www.strongopinionsweaklytyped.com/blog/2014/08/27/beware-the-siren-song-ofcomments/ [81] https://books.google.com/books?id=hjEFCAAAQBAJ [82] https://medium.cobeisfresh.com/why-code-without-comments-wastes-my-timec7251479975f#.g0jujzf7f [83] http://www.codethinked.com/dont-be-clever [84] https://github.com/realm/SwiftLint Copyright © 2017, The Pragmatic Bookshelf Chapter Good Code Good software code doesn’t just compile; it communicates It talks to you as a developer here and now and to future you, who will be maintaining this code It is comprehensible to your team and to anyone who will look at it externally It always chooses reliable and testable over clever, and it prefers to take an extra step or ten if needed to make its intent and outcome clear It’s code that thinks about scale, about living in a forest as well as being a single tree, and about being run a million times at once as well as once It’s code that believes in being broken down into sensible units instead of massive single implementations It’s code that exposes carefully considered and easily consumed APIs without sharing unnecessary internal implementation details It’s code that understands that it will be implemented not once or twice but reviewed and refactored to the best and most robust implementation possible It’s code that thinks globally and provides hooks for many cultures and multiabled users, which is a real code-level thing—how you add internationalization and accessibility is not an afterthought It’s code that thinks about not just the specifics of the destinations it will run on today but also how to adapt for when those destinations change over time It’s code that ships Good code works, does what is needed, and also is delivered on time “Great code leaves you in awe and inspired to go write your own great code.” —Dave DeLong Copyright © 2017, The Pragmatic Bookshelf You May Be Interested In… Select a cover for more information Core Data in Objective-C, Third Edition Core Data is Apple’s data storage framework: it’s powerful, built-in, and can integrate with iCloud Discover all of Core Data’s powerful capabilities, learn fundamental principles including thread and memory management, and add Core Data to both your iOS and OS X projects All examples in this edition are written in Objective-C and are based on OS X El Capitan and iOS Marcus S Zarra (238 pages) ISBN: 9781680501230 $38 Core Data in Swift Core Data is intricate, powerful, and necessary Discover the powerful capabilities integrated into Core Data, and how to use Core Data in your iOS and OS X projects All examples are current for macOS Sierra, iOS 10, and the latest release of Core Data All the code is written in Swift 3, including numerous examples of how best to integrate Core Data with Apple’s newest programming language Marcus Zarra (212 pages) ISBN: 9781680501704 $38 iOS 10 SDK Development All in on Swift! iOS 10 and Xcode make it clearer than ever that Swift is Apple’s language of the future Core frameworks have been redesigned to work better with Swift, and the language itself continues to evolve quickly iOS 10 SDK Development is the pure-Swift approach to developing for the iOS platform This completely revised and updated edition of the bestselling iOS guide shows you how to pull in the SDK’s enormous feature set and deliver powerful, real-world apps for iPhone and iPad using modern Swift programming techniques Chris Adamson with Janie Clayton (260 pages) ISBN: 9781680502107 $42.50 Exercises for Programmers When you write software, you need to be at the top of your game Great programmers practice to keep their skills sharp Get sharp and stay sharp with more than fifty practice exercises rooted in real-world scenarios If you’re a new programmer, these challenges will help you learn what you need to break into the field, and if you’re a seasoned pro, you can use these exercises to learn that hot new language for your next gig Brian P Hogan (118 pages) ISBN: 9781680501223 $24 Secure Your Node.js Web Application Cyber-criminals have your web applications in their crosshairs They search for and exploit common security mistakes in your web application to steal user data Learn how you can secure your Node.js applications, database and web server to avoid these security holes Discover the primary attack vectors against web applications, and implement security best practices and effective countermeasures Coding securely will make you a stronger web developer and analyst, and you’ll protect your users Karl Düüna (230 pages) ISBN: 9781680500851 $36 The Way of the Web Tester This book is for everyone who needs to test the web As a tester, you’ll automate your tests As a developer, you’ll build more robust solutions And as a team, you’ll gain a vocabulary and a means to coordinate how to write and organize automated tests for the web Follow the testing pyramid and level up your skills in user interface testing, integration testing, and unit testing Your new skills will free you up to other, more important things while letting the computer the one thing it’s really good at: quickly running thousands of repetitive tasks Jonathan Rasmusson (254 pages) ISBN: 9781680501834 $29 Liftoff, Second Edition Ready, set, liftoff! Align your team to one purpose: successful delivery Learn new insights and techniques for starting projects and teams the right way, with expanded concepts for planning, organizing, and conducting liftoff meetings Real-life stories illustrate how others have effectively started (or restarted) their teams and projects Master coaches Diana Larsen and Ainsley Nies have successfully “lifted off” numerous agile projects worldwide Are you ready for success? Diana Larsen and Ainsley Nies (170 pages) ISBN: 9781680501636 $24 Agile Retrospectives See how to mine the experience of your software development team continually throughout the life of the project The tools and recipes in this book will help you uncover and solve hidden (and not-sohidden) problems with your technology, your methodology, and those difficult “people issues” on your team Esther Derby and Diana Larsen, Foreword by Ken Schwaber (176 pages) ISBN: 9780977616640 $29.95 Mazes for Programmers A book on mazes? Seriously? Yes! Not because you spend your day creating mazes, or because you particularly like solving mazes But because it’s fun Remember when programming used to be fun? This book takes you back to those days when you were starting to program, and you wanted to make your code things, draw things, and solve puzzles It’s fun because it lets you explore and grow your code, and reminds you how it feels to just think Sometimes it feels like you live your life in a maze of twisty little passages, all alike Now you can code your way out Jamis Buck (286 pages) ISBN: 9781680500554 $38 Good Math Mathematics is beautiful—and it can be fun and exciting as well as practical Good Math is your guide to some of the most intriguing topics from two thousand years of mathematics: from Egyptian fractions to Turing machines; from the real meaning of numbers to proof trees, group symmetry, and mechanical computation If you’ve ever wondered what lay beyond the proofs you struggled to complete in high school geometry, or what limits the capabilities of the computer on your desk, this is the book for you Mark C Chu-Carroll (282 pages) ISBN: 9781937785338 $34 Your Code as a Crime Scene Jack the Ripper and legacy codebases have more in common than you’d think Inspired by forensic psychology methods, this book teaches you strategies to predict the future of your codebase, assess refactoring direction, and understand how your team influences the design With its unique blend of forensic psychology and code analysis, this book arms you with the strategies you need, no matter what programming language you use Adam Tornhill (218 pages) ISBN: 9781680500387 $36 The Nature of Software Development You need to get value from your software project You need it “free, now, and perfect.” We can’t get you there, but we can help you get to “cheaper, sooner, and better.” This book leads you from the desire for value down to the specific activities that help good Agile projects deliver better software sooner, and at a lower cost Using simple sketches and a few words, the author invites you to follow his path of learning and understanding from a half century of software development and from his engagement with Agile methods from their very beginning Ron Jeffries (178 pages) ISBN: 9781941222379 $24 Fire in the Valley In the 1970s, while their contemporaries were protesting the computer as a tool of dehumanization and oppression, a motley collection of college dropouts, hippies, and electronics fanatics were engaged in something much more subversive Obsessed with the idea of getting computer power into their own hands, they launched from their garages a hobbyist movement that grew into an industry, and ultimately a social and technological revolution What they did was invent the personal computer: not just a new device, but a watershed in the relationship between man and machine This is their story Michael Swaine and Paul Freiberger (424 pages) ISBN: 9781937785765 $34 The Healthy Programmer To keep doing what you love, you need to maintain your own systems, not just the ones you write code for Regular exercise and proper nutrition help you learn, remember, concentrate, and be creative—skills critical to doing your job well Learn how to change your work habits, master exercises that make working at a computer more comfortable, and develop a plan to keep fit, healthy, and sharp for years to come This book is intended only as an informative guide for those wishing to know more about health issues In no way is this book intended to replace, countermand, or conflict with the advice given to you by your own healthcare provider including Physician, Nurse Practitioner, Physician Assistant, Registered Dietician, and other licensed professionals Joe Kutner (254 pages) ISBN: 9781937785314 $36 ... in Swift 1!) to today, Swift settled down It decided exactly what kind of language it was going to be and has finally realized and expressed that language in a much more stable form A significant... surveys Swift language features you’ll want to standardize and lock down for better and more consistent code Chapter 3, Establish Preferred Practices Like any language, there’s always more than one... the Swift language and the Xcode tools that support Swift development The two Apple Swift[ 14] blogs[15] are updated about once a month, but coverage includes can’t-miss topics related to language