IOS 12 Programming Fundamentals With Swift - Krishna Adhikari

Transcription

Xc.22, 4S 1 if ti O Swrs dve a nC o 0,e1odiOS 12ProgrammingFundamentalswith SwiftSWIFT, XCODE, AND COCOA BASICSMatt Neuburg

FIFTH EDITIONiOS 12 ProgrammingFundamentals with SwiftSwift, Xcode, and Cocoa BasicsMatt NeuburgBoston

iOS 12 Programming Fundamentals with Swift, Fifth Editionby Matt NeuburgCopyright 2018 Matt Neuburg. All rights reserved.Printed in the United States of America.Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions arealso available for most titles (http://oreilly.com/safari). For more information, contact our corporate/insti‐tutional sales department: 800-998-9938 or corporate@oreilly.com.Editor: Rachel RoumeliotisProduction Editor: Kristen BrownProofreader: O’Reilly Production ServicesIndexer: Matt NeuburgApril 2015:October 2015:October 2016:October 2017:September 2018:Cover Designer: Karen MontgomeryInterior Designer: David FutatoIllustrator: Matt NeuburgFirst EditionSecond EditionThird EditionFourth EditionFifth EditionRevision History for the Fifth Edition2018-09-26: First releaseSee http://oreilly.com/catalog/errata.csp?isbn 9781492044550 for release details.The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. iOS 12 Programming Fundamentalswith Swift, the image of a harp seal, and related trade dress are trademarks of O’Reilly Media, Inc.While the publisher and the author have used good faith efforts to ensure that the information andinstructions contained in this work are accurate, the publisher and the author disclaim all responsibilityfor errors or omissions, including without limitation responsibility for damages resulting from the use ofor reliance on this work. Use of the information and instructions contained in this work is at your ownrisk. If any code samples or other technology this work contains or describes is subject to open sourcelicenses or the intellectual property rights of others, it is your responsibility to ensure that your usethereof complies with such licenses and/or rights.ISBN: 978-1-492-04455-0[LSI]

Table of ContentsPreface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiiiPart I.Language1. The Architecture of Swift. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Ground of BeingEverything Is an Object?Three Flavors of Object TypeVariablesFunctionsThe Structure of a Swift FileScope and LifetimeObject MembersNamespacesModulesInstancesWhy Instances?The Keyword selfPrivacyDesignObject Types and APIsInstance Creation, Scope, and LifetimeSummary and Conclusion3566891113131415171920222325252. Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27Function Parameters and Return ValueVoid Return Type and ParametersFunction SignatureExternal Parameter Names27313232iii

OverloadingDefault Parameter ValuesVariadic ParametersIgnored ParametersModifiable ParametersFunction in FunctionRecursionFunction As ValueAnonymous FunctionsDefine-and-CallClosuresHow Closures Improve CodeFunction Returning FunctionClosure Setting a Captured VariableClosure Preserving Its Captured EnvironmentEscaping ClosuresCurried FunctionsFunction References and SelectorsFunction Reference 64653. Variables and Simple Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69Variable Scope and LifetimeVariable DeclarationComputed InitializerComputed VariablesSetter ObserversLazy InitializationBuilt-In Simple TypesBoolNumbersStringCharacter and String 31054. Object Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119Object Type Declarations and FeaturesInitializersPropertiesMethodsiv Table of Contents119121127130

SubscriptsNested Object TypesInstance ReferencesEnumsRaw ValuesAssociated ValuesEnum Case IterationEnum InitializersEnum PropertiesEnum MethodsWhy Enums?StructsStruct Initializers, Properties, and MethodsStruct As NamespaceClassesValue Types and Reference TypesSubclass and SuperclassClass InitializersClass DeinitializerClass Properties and MethodsPolymorphismCastingCasting DownType Testing and Casting Down SafelyType Testing and Casting OptionalsBridging to Objective-CType ReferencesFrom Instance to TypeType as ValueThe Keyword SelfComparing TypesSummary of Type TerminologyProtocolsWhy Protocols?Protocol Type Testing and CastingDeclaring a ProtocolProtocol CompositionOptional Protocol MembersClass ProtocolImplicitly Required InitializersLiteral e of Contents v

Generic DeclarationsContradictory ResolutionType ConstraintsExplicit SpecializationGeneric InvarianceAssociated Type ChainsWhere ClausesExtensionsExtending Object TypesExtending ProtocolsExtending GenericsUmbrella TypesAnyAnyObjectAnyClassCollection 2152172192192212232242242402475. Flow Control and More. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253Flow ControlBranchingLoopsJumpingPrivacyPrivate and FileprivatePublic and OpenPrivacy RulesIntrospectionOperatorsSynthesized Protocol ImplementationsKey PathsDynamic Member LookupMemory ManagementMemory Management of Reference TypesExclusive Access to Value TypesPart II.vi IDETable of 301308

6. Anatomy of an Xcode Project. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313New ProjectThe Project WindowThe Navigator PaneThe Utilities PaneThe EditorThe Project File and Its DependentsWhat’s In the Project FolderGroupsThe TargetBuild PhasesBuild SettingsConfigurationsSchemes and DestinationsFrom Project to Built AppBuild SettingsProperty List SettingsNib FilesAdditional ResourcesCode FilesFrameworks and SDKsThe App Launch ProcessThe Entry PointUIApplicationMainApp Without a StoryboardRenaming Parts of a 383383393403423433453453463483497. Nib Management. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351The Nib Editor InterfaceDocument OutlineCanvasInspectors and LibrariesNib LoadingWhen Nibs Are LoadedManual Nib LoadingConnectionsOutletsThe Nib OwnerAutomatically Configured NibsMisconfigured OutletsDeleting an OutletMore Ways to Create able of Contents vii

Outlet CollectionsAction ConnectionsMore Ways to Create ActionsMisconfigured ActionsConnections Between Nibs — Not!Additional Configuration of Nib-Based Instances3743753773793793808. Documentation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385The Documentation WindowClass Documentation PagesQuick HelpSymbol DeclarationsHeader FilesSample CodeInternet Resources3853863903923933943949. Life Cycle of a Project. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397Environmental DependenciesPermissible Runtime EnvironmentBackward CompatibilityDevice TypeArguments and Environment VariablesConditional CompilationVersion ControlEditing and Navigating Your CodeAutocompletionSnippetsFix-it and Live Syntax CheckingNavigationFindingRefactoringRunning in the SimulatorDebuggingCaveman DebuggingThe Xcode DebuggerTestingUnit TestsInterface TestsCleanRunning on a DeviceObtaining a Developer Program MembershipSigning an Appviii Table of 416417417420427428431433433434435

Automatic SigningManual SigningRunning the AppManaging Development Certificates and DevicesProfilingGaugesMemory DebuggingInstrumentsLocalizationDistributionMaking an ArchiveThe Distribution CertificateThe Distribution ProfileDistribution for TestingFinal App PreparationsScreenshots and Video PreviewsProperty List SettingsSubmission to the App StorePart 61463464Cocoa10. Cocoa Classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469SubclassingCategories and ExtensionsHow Swift Uses ExtensionsHow You Use ExtensionsHow Cocoa Uses CategoriesProtocolsInformal ProtocolsOptional MethodsSome Foundation ClassesNSRange and NSNotFoundNSString and FriendsNSDate and FriendsNSNumberNSValueNSDataNSMeasurement and FriendsEquality, Hashability, and ComparisonNSArray and NSMutableArrayNSDictionary and 83486487489490491491494496Table of Contents ix

NSSet and FriendsNSIndexSetNSNullImmutable and MutableProperty ListsCodableAccessors, Properties, and Key–Value CodingSwift AccessorsKey–Value CodingUses of Key–Value CodingKVC and OutletsCocoa Key PathsThe Secret Life of NSObject49649749849850050150450550750851051051111. Cocoa Events. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513Reasons for EventsSubclassingNotificationsReceiving a NotificationUnregisteringPosting a NotificationTimerDelegationCocoa DelegationImplementing DelegationData SourcesActionsThe Responder ChainDeferring ResponsibilityNil-Targeted ActionsKey–Value ObservingRegistration and NotificationUnregisteringKey–Value Observing ExampleSwamped by EventsDelayed 53153253353453553653754012. Memory Management. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543Principles of Cocoa Memory ManagementRules of Cocoa Memory ManagementWhat ARC Is and What It DoesHow Cocoa Objects Manage Memoryx Table of Contents543544545546

Autorelease PoolMemory Management of Instance PropertiesRetain Cycles and Weak ReferencesUnusual Memory Management SituationsNotification ObserversKVO ObserversTimersOther Unusual SituationsNib Loading and Memory ManagementMemory Management of CFTypeRefsProperty Memory Management PoliciesDebugging Memory Management Mistakes54754955055255255455455655655755956113. Communication Between Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 563Visibility by InstantiationVisibility by RelationshipGlobal VisibilityNotifications and Key–Value . C, Objective-C, and Swift. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 607Table of Contents xi

PrefaceOn June 2, 2014, Apple’s WWDC keynote address ended with a shocking announce‐ment: “We have a new programming language.” This came as a huge surprise to thedeveloper community, which was accustomed to Objective-C, warts and all, anddoubted that Apple could ever possibly relieve them from the weight of its venerablelegacy. The developer community, it appeared, had been wrong.Having picked themselves up off the floor, developers immediately began to considerthis new language — Swift — studying it, critiquing it, and deciding whether to use it.My own first move was to translate all my existing iOS apps into Swift; this wasenough to convince me that Swift deserved to be, and probably would be, adopted bynew students of iOS programming, and that my books, therefore, should henceforthassume that readers are using Swift.That decision has proven prophetic. Programmers of iOS have flocked to Swift inincreasing numbers, and Swift itself has only improved. My iOS apps (such as Diabel‐li’s Theme, LinkSame, Zotz!, TidBITS News, and my Latin and Greek flashcard apps)have all been rewritten in Swift, and are far easier for me to understand and maintainthan their Objective-C originals.Xcode 10 comes with Swift 4.2. The language has evolved greatly in its details and inthe nature of its integration with the Cocoa libraries that underlie iOS programming,but its spirit has remained constant. The Swift language is designed from the groundup with these salient features:Object-orientationSwift is a modern, object-oriented language. It is purely object-oriented: “Every‐thing is an object.”ClaritySwift is easy to read and easy to write. Its syntax is clear, consistent, and explicit,with few hidden shortcuts and minimal syntactic trickery.xiii

SafetySwift enforces strong typing to ensure that it knows, and that you know, what thetype of every object reference is at every moment.EconomySwift is a fairly small language, providing some basic types and functionalitiesand no more. The rest must be provided by your code, or by libraries of code thatyou use — such as Cocoa.Memory managementSwift manages memory automatically. You will rarely have to concern yourselfwith memory management.Cocoa compatibilityThe Cocoa APIs are written primarily in C and Objective-C. Swift is explicitlydesigned to interface with most of the Cocoa APIs.These features make Swift an excellent language for learning to program iOS.The alternative, Objective-C, still exists, and you can use it if you like. Indeed, it iseasy to write an app that includes both Swift code and Objective-C code; and you mayhave reason to do so. Objective-C, however, lacks the very advantages that Swiftoffers. Objective-C agglomerates object-oriented features onto C. It is therefore onlypartially object-oriented; it has both objects and scalar data types, and its objects haveto be slotted into one particular C data type (pointers). Its syntax can be difficult andtricky; reading and writing nested method calls can make one’s eyes glaze over, and itinvites hacky habits such as implicit nil-testing. Its type checking can be and fre‐quently is turned off, resulting in programmer errors where a message is sent to thewrong type of object and the program crashes.Recent revisions and additions to Objective-C — ARC, synthesis and autosynthesis,improved literal array and dictionary syntax, blocks — have made it easier and moreconvenient, but such patches have also made the language even larger and possiblyeven more confusing. Because Objective-C must encompass C, there are limits tohow far it can be extended and revised. Swift, on the other hand, is a clean start. Ifyou were to dream of completely revising Objective-C to create a better Objective-C,Swift might be what you would dream of. It puts a modern, rational front endbetween you and the Cocoa Objective-C APIs.Still, the reader may also need some awareness of Objective-C (including C). TheFoundation and Cocoa APIs, the built-in commands with which your code mustinteract in order to make anything happen on an iOS device, are still written in C andObjective-C. In order to interact with them, you might have to know what those lan‐guages would expect.xiv Preface

Therefore, although I do not attempt to teach Objective-C in this book, I do describeit in enough detail to allow you to read it when you encounter it in the documenta‐tion and on the Internet, and I occasionally show some Objective-C code. Part III, onCocoa, is really all about learning to think the way Objective-C thinks — because thestructure and behavior of the Cocoa APIs are fundamentally based on Objective-C.And the book ends with an appendix that details how Swift and Objective-C commu‐nicate with one another, as well as explaining how your app can be written partly inSwift and partly in Objective-C.The Scope of This BookThis book is actually one of a pair with my Programming iOS 12, which picks upexactly where this book leaves off. They complement and supplement one another.The two-book architecture should, I believe, render the size and scope of each booktractable for readers. Together, they provide a complete grounding in the knowledgeneeded to begin writing iOS apps; thus, when you do start writing iOS apps, you’llhave a solid and rigorous understanding of what you are doing and where you areheading. If writing an iOS program is like building a house of bricks, this bookteaches you what a brick is and how to handle it, while Programming iOS 12 handsyou some actual bricks and tells you how to assemble them.When you have read this book, you’ll know about Swift, Xcode, and the underpin‐nings of the Cocoa framework, and you will be ready to proceed directly to Program‐ming iOS 12. Conversely, Programming iOS 12 assumes a knowledge of this book; itbegins, like Homer’s Iliad, in the middle of the story, with the reader jumping with allfour feet into views and view controllers, and with a knowledge of the language andthe Xcode IDE already presupposed. If you started reading Programming iOS 12 andwondered about such unexplained matters as Swift language basics, theUIApplicationMain function, the nib-loading mechanism, Cocoa patterns of delega‐tion and notification, and retain cycles, wonder no longer — I didn’t explain themthere because I do explain them here.The three parts of this book teach the underlying basis of all iOS programming: Part I introduces the Swift language, from the ground up — I do not assume thatyou know any other programming languages. My way of teaching Swift is differ‐ent from other treatments, such as Apple’s; it is systematic and Euclidean, withpedagogical building blocks piled on one another in what I regard as the mosthelpful order. At the same time, I have tried to confine myself to the essentials.Swift is not a big language, but it has some subtle and unusual corners. You don’tneed to dive deep into all of these, and my discussion will leave many of themunexplored. You will probably never encounter them, and if you do, you willhave entered an advanced Swift world outside the scope of this discussion. Togive an obvious example, readers may be surprised to find that I never mentionPreface xv

Swift playgrounds or the REPL. My focus here is real-life iOS programming, andmy explanation of Swift therefore concentrates on those common, practicalaspects of the language that, in my experience, actually come into play in thecourse of programming iOS. Part II turns to Xcode, the world in which all iOS programming ultimately takesplace. It explains what an Xcode project is and how it is transformed into an app,and how to work comfortably and nimbly with Xcode to consult the documenta‐tion and to write, navigate, and debug code, as well as how to bring your appthrough the subsequent stages of running on a device and submission to the AppStore. There is also a very important chapter on nibs and the nib editor (InterfaceBuilder), including outlets and actions as well as the mechanics of nib loading;however, such specialized topics as autolayout constraints in the nib are post‐poned to the other book. Part III introduces the Cocoa Touch framework. When you program for iOS, youtake advantage of a suite of frameworks provided by Apple. These frameworks,taken together, constitute Cocoa; the brand of Cocoa that provides the API forprogramming iOS is Cocoa Touch. Your code will ultimately be almost entirelyabout communicating with Cocoa. The Cocoa Touch frameworks provide theunderlying functionality that any iOS app needs to have. But to use a framework,you have to think the way the framework thinks, put your code where the frame‐work expects it, and fulfill many obligations imposed on you by the framework.To make things even more interesting, Cocoa uses Objective-C, while you’ll beusing Swift: you need to know how your Swift code will interface with Cocoa’sfeatures and behaviors. Cocoa provides important foundational classes and addslinguistic and architectural devices such as categories, protocols, delegation, andnotifications, as well as the pervasive responsibilities of memory management.Key–value coding and key–value observing are also discussed here.The reader of this book will thus get a thorough grounding in the fundamentalknowledge and techniques that any good iOS programmer needs. The book itselfdoesn’t show how to write any particularly interesting iOS apps, but it does constantlyuse my own real apps and real programming situations to illustrate and motivate itsexplanations. And then you’ll be ready for Programming iOS 12, of course!VersionsThis book is geared to Swift 4.2, iOS 12, and Xcode 10.In general, only very minimal attention is given to earlier versions of iOS and Xcode.It is not my intention to embrace in this book any detailed knowledge about earlierversions of the software, which is, after all, readily and compendiously available in myearlier books. The book does contain, nevertheless, a few words of advice about back‐ward compatibility (especially in Chapter 9).xvi Preface

A word about method names. I generally give method names in Swift, in the style of afunction reference (as described in Chapter 2) — that is, the name plus parenthesescontaining the parameter labels followed by colon. Now and then, if a method isalready under discussion and there is no ambiguity, I’ll use the bare name. In a fewplaces, such as Appendix A, where the Objective-C language is explicitly under dis‐cussion, I use Objective-C method names.Please bear in mind that Apple continues to make adjustments to the Swift language.I have tried to keep my code up-to-date right up to the moment when the manuscriptleft my hands; but if, at some future time, a new version of Xcode is released alongwith a new version of Swift, some of the code in this book, and even some informa‐tion about Swift itself, might be slightly incorrect. Please make allowances, and beprepared to compensate.Screenshots of Xcode were taken using Xcode 10 under macOS 10.13 High Sierra. Ihave not upgraded my machine to macOS 10.14 Mojave, because at the time of thiswriting it was too new to be trusted with mission-critical work. If you are braver thanI am and running Mojave, your interface may naturally look slightly different fromthe screenshots (especially if you’re using “dark mode”), but this difference will beminimal and shouldn’t cause any confusion.AcknowledgmentsMy thanks go first and foremost to the people at O’Reilly Media who have made writ‐ing a book so delightfully easy: Rachel Roumeliotis, Sarah Schneider, Kristen Brown,Dan Fauxsmith, Adam Witwer, and Sanders Kleinfeld come particularly to mind.And let’s not forget my first and long-standing editor, Brian Jepson, whose influenceis present throughout.As in the past, I have been greatly aided by some fantastic software, whose excellencesI have appreciated at every moment of the process of writing this book. I should liketo mention, in particular: git (http://git-scm.com) Sourcetree (http://www.sourcetreeapp.com) TextMate (http://macromates.com) AsciiDoc (http://www.methods.co.nz/asciidoc) Asciidoctor (http://asciidoctor.org) BBEdit (http://barebones.com/products/bbedit/) EasyFind e.html) Snapz Pro X (http://www.ambrosiasw.com) GraphicConverter (http://www.lemkesoft.com)Preface xvii

OmniGraffle (http://www.omnigroup.com)The book was typed and edited entirely on my faithful Unicomp Model M keyboard(http://pckeyboard.com), without which I could never have done so much writing overso long a period so painlessly. For more about my physical work environment, seehttp://matt.neuburg.usesthis.com.From the Programming iOS 4 PrefaceA programming framework has a kind of personality, an overall flavor that providesan insight into the goals and mindset of those who created it. When I first encoun‐tered Cocoa Touch, my assessment of its personality was: “Wow, the people whowrote this are really clever!” On the one hand, the number of built-in interfaceobjects was severely and deliberately limited; on the other hand, the power and flexi‐bility of some of those objects, especially such things as UITableView, was greatlyenhanced over their OS X counterparts. Even more important, Apple created a partic‐ularly brilliant way (UIViewController) to help the programmer make entire blocksof interface come and go and supplant one another in a controlled, hierarchical man‐ner, thus allowing that tiny iPhone display to unfold virtually into multiple interfaceworlds within a single app without the user becoming lost or confused.The popularity of the iPhone, with its largely free or very inexpensive apps, and thesubsequent popularity of the iPad, have brought and will continue to bring into thefold many new programmers who see programming for these devices as worthwhileand doable, even though they may not have felt the same way about OS X. Apple’sown annual WWDC developer conventions have reflected this trend, with theiremphasis shifted from OS X to iOS instruction.The widespread eagerness to program iOS, however, though delightful on the onehand, has also fostered a certain tendency to try to run without first learning to walk.iOS gives the programmer mighty powers that can seem as limitless as imaginationitself, but it also has fundamentals. I often see questions online from programmerswho are evidently deep into the creation of some interesting app, but who are stymiedin a way that reveals quite clearly that they are unfamiliar with the basics of the veryworld in which they are so happily cavorting.It is this state of affairs that has motivated me to write this book, which is intended toground the reader in the fundamentals of iOS. I love Cocoa and have long wished towrite about it, but it is iOS and its popularity that has given me a proximate excuse todo so. Here I have attempted to marshal and expound, in what I hope is a pedagogi‐cally helpful and instructive yet ruthlessly Euclidean and logical order, the principlesand elements on which sound iOS programming rests. My hope, as with my previousbooks, is that you will both read this book cover to cover (learning something newoften enough to keep you turning the pages) and keep it by you as a handy reference.xviii Preface

This book is not intended to disparage Apple’s own documentation and exampleprojects. They are wonderful resources and have become more wonderful as timegoes on. I have depended heavily on them in the preparation of this book. But I alsofind that they don’t fulfill the same function as a reasoned, ordered presentation ofthe facts. The online documentation must make assumptions as to how much youalready know; it can’t guarantee that you’ll approach it in a given order. And onlinedocumentation is more suitable to reference than to instruction. A fully writtenexample, no matter how well commented, is difficult to follow; it demonstrates, but itdoes not teach.A book, on the other hand, has numbered chapters and sequential pages; I canassume you know views before you know view controllers for the simple reason thatPart I precedes Part II. And along with facts, I also bring to the table a degree of expe‐rience, which I try to communicate to you. Throughout this book you’ll find mereferring to “common beginner mistakes”; in most cases, these are mistakes that Ihave made myself, in addition to seeing others make them. I try to tell you what thepitfalls are because I assume that, in the course of things, you will otherwise fall intothem just as naturally as I did as I was learning. You’ll also see me construct manyexamples piece by piece or extract and explain just one tiny portion of a larger app. Itis not a massive finished program that teaches programming, but an exposition of thethought process that developed that program. It is this thought process, more thananything else, that I hope you will gain from reading this book.Conventions Used in This BookThe following typographical conventions are used in this book:ItalicIndicates new terms, URLs, email addresses, filenames, and file extensions.Constant widthUsed for program listings, as well as within paragraphs to refer to program ele‐ments such as variable or function names, databases, data types, environmentvariables, statements, and keywords.Constant width boldShows commands or other text that should be typed literally by the user.Constant width italicShows text that should be replaced with user-supplied values or by values deter‐mined by context.This element signifies a tip or suggestion.Preface xix

This element signifies a general note.This element indicates a warning or caution.Using Code ExamplesSupplemental material (code examples, exercises, etc.) is available for download Examples.This book is here to help you get your job done. In general, if example code is offeredwith this book, you may use it in your programs and documentation. You do notneed to contact us for permission unless you’re reproducing a significant portion ofthe code. For example, writing a program that uses several chunks of code from thisbook does not require permission. Selling or distributing a CD-ROM of examplesfrom O’Reilly books does require permission. Answering a question by citing thisbook and quoting example code does not require permission. Incorporating a signifi‐cant amount of example code from this book into your product’s documentation doesrequire permission.We appreciate, but do not require, attribution. An attribution usually includes thetitle, author, publisher, and ISBN. For example: “iOS 12 Programming Fundamentalswith Swift by Matt Neuburg (O’Reilly). Copyright 2018 Matt Neuburg,978-1-492-04455-0.”If you feel your use of code examples falls out

Swift manages memory automatically. You will rarely have to concern yourself with memory management. Cocoa compatibility The Cocoa APIs are written primarily in C and Objective-C. Swift is explicitly designed to interface with most of the Cocoa APIs. These features make Swift an excellent language for learning to program iOS.