The goal of this book is to teach the skills necessary to build iOS 14 applications using SwiftUI, Xcode 12 and the Swift 5.3 programming language.Beginning with the basics, this book provides an outline of the steps necessary to set up an iOS development environment together with an introduction to the use of Swift Playgrounds to learn and experiment with Swift.The book also includes indepth chapters introducing the Swift 5.3 programming language including data types, control flow, functions, objectoriented programming, property wrappers and error handling.An introduction to the key concepts of SwiftUI and project architecture is followed by a guided tour of Xcode in SwiftUI development mode. The book also covers the creation of custom SwiftUI views and explains how these views are combined to create user interface layouts including the use of stacks, frames and forms.Other topics covered include data handling using state properties in addition to observable, state and environment objects, as are key user interface design concepts such as modifiers, lists, tabbed views, context menus and user interface navigation, and outline groups.The book also includes chapters covering graphics drawing, user interface animation, view transitions and gesture handling, WidgetKit, documentbased apps and SiriKit integration.Chapters are also provided explaining how to integrate SwiftUI views into existing UIKitbased projects and explains the integration of UIKit code into SwiftUI.Finally, the book explains how to package up a completed app and upload it to the App Store for publication.Along the way, the topics covered in the book are put into practice through detailed tutorials, the source code for which is also available for download.The aim of this book, therefore, is to teach you the skills necessary to build your own apps for iOS 14 using SwiftUI. Assuming you are ready to download the iOS 14 SDK and Xcode 12 and have an Apple Mac system you are ready to get started.
SwiftUI Essentials iOS 14 Edition SwiftUI Essentials – iOS 14 Edition ISBN-13: 978-1-951442-27-9 © 2020 Neil Smyth / Payload Media, Inc All Rights Reserved This book is provided for personal use only Unauthorized use, reproduction and/or distribution strictly prohibited All rights reserved The content of this book is provided for informational purposes only Neither the publisher nor the author offers any warranties or representation, express or implied, with regard to the accuracy of information contained in this book, nor they accept any liability for any loss or damage arising from any errors or omissions This book contains trademarked terms that are used solely for editorial purposes and to the benefit of the respective trademark owner The terms used within this book are not intended as infringement of any trademarks Rev: 1.0 Table of Contents Start Here 1.1 For Swift Programmers 1.2 For Non-Swift Programmers 1.3 Source Code Download 1.4 Feedback 1.5 Errata Joining the Apple Developer Program 2.1 Downloading Xcode 12 and the iOS 14 SDK 2.2 Apple Developer Program 2.3 When to Enroll in the Apple Developer Program? 2.4 Enrolling in the Apple Developer Program 2.5 Summary Installing Xcode 12 and the iOS 14 SDK 3.1 Identifying Your macOS Version 3.2 Installing Xcode 12 and the iOS 14 SDK 3.3 Starting Xcode 3.4 Adding Your Apple ID to the Xcode Preferences 3.5 Developer and Distribution Signing Identities 3.6 Summary An Introduction to Xcode 12 Playgrounds 4.1 What is a Playground? 4.2 Creating a New Playground 4.3 A Swift Playground Example 4.4 Viewing Results 4.5 Adding Rich Text Comments 4.6 Working with Playground Pages 4.7 Working with SwiftUI and Live View in Playgrounds 4.8 Summary Swift Data Types, Constants and Variables 5.1 Using a Swift Playground 5.2 Swift Data Types 5.2.1 Integer Data Types 5.2.2 Floating Point Data Types 5.2.3 Bool Data Type 5.2.4 Character Data Type 5.2.5 String Data Type 5.2.6 Special Characters/Escape Sequences 5.3 Swift Variables 5.4 Swift Constants 5.5 Declaring Constants and Variables 5.6 Type Annotations and Type Inference 5.7 The Swift Tuple 5.8 The Swift Optional Type 5.9 Type Casting and Type Checking 5.10 Summary Swift Operators and Expressions 6.1 Expression Syntax in Swift 6.2 The Basic Assignment Operator 6.3 Swift Arithmetic Operators 6.4 Compound Assignment Operators 6.5 Comparison Operators 6.6 Boolean Logical Operators 6.7 Range Operators 6.8 The Ternary Operator 6.9 Nil Coalescing Operator 6.10 Bitwise Operators 6.10.1 Bitwise NOT 6.10.2 Bitwise AND 6.10.3 Bitwise OR 6.10.4 Bitwise XOR 6.10.5 Bitwise Left Shift 6.10.6 Bitwise Right Shift 6.11 Compound Bitwise Operators 6.12 Summary Swift Control Flow 7.1 Looping Control Flow 7.2 The Swift for-in Statement 7.2.1 The while Loop 7.3 The repeat while loop 7.4 Breaking from Loops 7.5 The continue Statement 7.6 Conditional Control Flow 7.7 Using the if Statement 7.8 Using if else … Statements 7.9 Using if else if Statements 7.10 The guard Statement 7.11 Summary The Swift Switch Statement 8.1 Why Use a switch Statement? 8.2 Using the switch Statement Syntax 8.3 A Swift switch Statement Example 8.4 Combining case Statements 8.5 Range Matching in a switch Statement 8.6 Using the where statement 8.7 Fallthrough 8.8 Summary Swift Functions, Methods and Closures 9.1 What is a Function? 9.2 What is a Method? 9.3 How to Declare a Swift Function 9.4 Implicit Returns from Single Expressions 9.5 Calling a Swift Function 9.6 Handling Return Values 9.7 Local and External Parameter Names 9.8 Declaring Default Function Parameters 9.9 Returning Multiple Results from a Function 9.10 Variable Numbers of Function Parameters 9.11 Parameters as Variables 9.12 Working with In-Out Parameters 9.13 Functions as Parameters 9.14 Closure Expressions 9.15 Shorthand Argument Names 9.16 Closures in Swift 9.17 Summary 10 The Basics of Swift Object-Oriented Programming 10.1 What is an Instance? 10.2 What is a Class? 10.3 Declaring a Swift Class 10.4 Adding Instance Properties to a Class 10.5 Defining Methods 10.6 Declaring and Initializing a Class Instance 10.7 Initializing and De-initializing a Class Instance 10.8 Calling Methods and Accessing Properties 10.9 Stored and Computed Properties 10.10 Lazy Stored Properties 10.11 Using self in Swift 10.12 Understanding Swift Protocols 10.13 Opaque Return Types 10.14 Summary 11 An Introduction to Swift Subclassing and Extensions 11.1 Inheritance, Classes and Subclasses 11.2 A Swift Inheritance Example 11.3 Extending the Functionality of a Subclass 11.4 Overriding Inherited Methods 11.5 Initializing the Subclass 11.6 Using the SavingsAccount Class 11.7 Swift Class Extensions 11.8 Summary 12 An Introduction to Swift Structures and Enumerations 12.1 An Overview of Swift Structures 12.2 Value Types vs Reference Types 12.3 When to Use Structures or Classes 12.4 An Overview of Enumerations 12.5 Summary 13 An Introduction to Swift Property Wrappers 13.1 Understanding Property Wrappers 13.2 A Simple Property Wrapper Example 13.3 Supporting Multiple Variables and Types 13.4 Summary 14 Working with Array and Dictionary Collections in Swift 14.1 Mutable and Immutable Collections 14.2 Swift Array Initialization 14.3 Working with Arrays in Swift 14.3.1 Array Item Count 14.3.2 Accessing Array Items 14.4 Random Items and Shuffling 14.5 Appending Items to an Array 14.5.1 Inserting and Deleting Array Items 14.6 Array Iteration 14.7 Creating Mixed Type Arrays 14.8 Swift Dictionary Collections 14.9 Swift Dictionary Initialization 14.10 Sequence-based Dictionary Initialization 14.11 Dictionary Item Count 14.12 Accessing and Updating Dictionary Items 14.13 Adding and Removing Dictionary Entries 14.14 Dictionary Iteration 14.15 Summary 15 Understanding Error Handling in Swift 5 15.1 Understanding Error Handling 15.2 Declaring Error Types 15.3 Throwing an Error 15.4 Calling Throwing Methods and Functions 15.5 Accessing the Error Object 15.6 Disabling Error Catching 15.7 Using the defer Statement 15.8 Summary 16 An Overview of SwiftUI 16.1 UIKit and Interface Builder 16.2 SwiftUI Declarative Syntax 16.3 SwiftUI is Data Driven 16.4 SwiftUI vs UIKit 16.5 Summary 17 Using Xcode in SwiftUI Mode 17.1 Starting Xcode 12 17.2 Creating a SwiftUI Project 17.3 Xcode in SwiftUI Mode 17.4 The Preview Canvas 17.5 Preview Pinning 17.6 The Preview Toolbar 17.7 Modifying the Design 17.8 Editor Context Menu 17.9 Previewing on Multiple Device Configurations 17.10 Running the App on a Simulator 17.11 Running the App on a Physical iOS Device 17.12 Managing Devices and Simulators 17.13 Enabling Network Testing 17.14 Dealing with Build Errors 17.15 Monitoring Application Performance 17.16 Exploring the User Interface Layout Hierarchy 17.17 Summary 18 SwiftUI Architecture 18.1 SwiftUI App Hierarchy 18.2 App 18.3 Scenes 18.4 Views 18.5 Summary 19 The Anatomy of a Basic SwiftUI Project 19.1 Creating an Example Project 19.2 Project Folders 19.3 The DemoProjectApp.swift File 19.4 The ContentView.swift File 19.5 Assets.xcassets 19.6 Info.plist 19.7 Summary 20 Creating Custom Views with SwiftUI 20.1 SwiftUI Views 20.2 Creating a Basic View 20.3 Adding Additional Views 20.4 Working with Subviews 20.5 Views as Properties 20.6 Modifying Views 20.7 Working with Text Styles 20.8 Modifier Ordering 20.9 Custom Modifiers 20.10 Basic Event Handling 20.11 Building Custom Container Views 20.12 Working with the Label View 20.13 Summary 21 SwiftUI Stacks and Frames 21.1 SwiftUI Stacks 21.2 Spacers, Alignment and Padding 21.3 Container Child Limit 21.4 Text Line Limits and Layout Priority 21.5 Traditional vs Lazy Stacks 21.6 SwiftUI Frames 21.7 Frames and the Geometry Reader 21.8 Summary 22 SwiftUI State Properties, Observable, State and Environment Objects 22.1 State Properties 22.2 State Binding 22.3 Observable Objects 22.4 State Objects 22.5 Environment Objects 22.6 Summary 23 A SwiftUI Example Tutorial 23.1 Creating the Example Project 23.2 Reviewing the Project 23.3 Adding a VStack to the Layout 23.4 Adding a Slider View to the Stack 23.5 Adding a State Property 23.6 Adding Modifiers to the Text View 23.7 Adding Rotation and Animation 23.8 Adding a TextField to the Stack 23.9 Adding a Color Picker 23.10 Tidying the Layout 23.11 Summary 24 SwiftUI Lifecycle Event Modifiers 24.1 Creating the LifecycleDemo Project 24.2 Designing the App 24.3 The onAppear and onDisappear Modifiers 24.4 The onChange Modifier 24.5 ScenePhase and the onChange Modifier 24.6 Summary 25 SwiftUI Observable and Environment Objects – A Tutorial 25.1 About the ObservableDemo Project 25.2 Creating the Project 25.3 Adding the Observable Object 25.4 Designing the ContentView Layout 25.5 Adding the Second View 25.6 Adding Navigation 25.7 Using an Environment Object 25.8 Summary 26 SwiftUI Data Persistence using AppStorage and SceneStorage 26.1 The @SceneStorage Property Wrapper 26.2 The @AppStorage Property Wrapper 26.3 Creating and Preparing the StorageDemo Project 26.4 Using Scene Storage 26.5 Using App Storage 26.6 Storing Custom Types 26.7 Summary 27 SwiftUI Stack Alignment and Alignment Guides 27.1 Container Alignment 27.2 Alignment Guides 27.3 Using the Alignment Guides Tool 27.4 Custom Alignment Types 27.5 Cross Stack Alignment 27.6 ZStack Custom Alignment 27.7 Summary 28 SwiftUI Lists and Navigation 28.1 SwiftUI Lists 28.2 SwiftUI Dynamic Lists 28.3 SwiftUI NavigationView and NavigationLink 28.4 Making the List Editable 28.5 Hierarchical Lists adding 446 HStack 136, 145 I if else if Statements 45 if else … Statements 44 if Statement 44 Image view 145 implicit alignment 199 Implicit Animation 287 implicitly unwrapped 29 INExtension class 328 Info.plist 131 Inheritance, Classes and Subclasses 71 INInteraction 340, 364 init method 63 in keyword 58 INMessagesDomainHandling 338 inout keyword 56 In-Out Parameters 55 INPreferences 334 InSearchForPhotosIntent 329 INSendMessageIntent 362 Instance Properties 62 IntentConfiguration 387 Intent Definition file 361 Intent Definition File introduction to 361 IntentHandler 351 Intent Response 373 Intents Extension 329 Intents.intentdefinition 370 IntentsSupported 335 IntentTimelineProvider 402, 414 IntentViewController class 328 Interface Builder 103 INUIAddVoiceShortcutButton 364 iOS 13 adoption rate 105 iOS 13 SDK installation 7 system requirements 7 iOS Distribution Certificate 455 is keyword 31 J JSON 226 loading 226 L Label view 143 Layout Hierarchy 123 Layout Priority 150 lazy keyword 67 LazyHGrid 257, 265 LazyHStack 151 Lazy properties 66 Lazy Stacks 151 vs traditional 151 LazyVGrid 257 LazyVStack 151 Left Shift Operator 38 Library panel 114 linear 288 LinearGradient 284 Lists hierarchical 222 listStyle() modifier 250 List view 215 adding navigation 232 dynamic 216 listStyle() modifier 250 making editable 220 SidebarListStyle 250 List view tutorial 225 Live Preview 112 Live View 17 local parameter names 53 Loops breaking from 43 M Main.storyboard file 445 makeBody() 308 makeCoordinator() 429, 433, 434 makeUIView() 428 mathematical expressions 33 Methods declaring 62 Mixed Type Arrays 92 modifier() method 140 Modifiers 140 multiplatform project 129 Multiple Device Configurations 117 N Navigation 215 implementing 187 tutorial 225 navigationBarItems() modifier 221, 235 navigationBarTitle() modifier 235 NavigationLink 219, 236 NavigationView 219 Network Testing 121 new line 24 nil coalescing operator 36 NOT (!) operator 35 NSExtensionAttributes 335 NSInteraction 330 NSSiriUsageDescription 367 NSUserActivity 359 NSUserActivityTypes 359 NSUserObject 357 NSVocabulary class 331 O Objective-C 21 Observable Object example 183 ObservableObject 157, 160 ObservableObject protocol 160 onAppear() 292, 293 onChanged() 298 onDelete() 220, 236 onMove() 221, 236 onOpenUrl() 417 Opaque Return Types 69 operands 33 optional implicitly unwrapped 29 optional binding 28 Optional Type 27 OR (||) operator 35 OR operator 38 OutlineGroup 223, 239, 251 tutorial 247 using 242 Overlays 279 P Padding 147 padding() modifier 147 PageTabViewStyle() 270 Parameter Names 53 external 53 local 53 parent class 61 Path object 280 Paths 280 Performance monitoring 122 PHFetchOptions 355 PHImageManager 357 Physical iOS Device 120 running app on 120 Picker view 157 example 172 Playground 11 creating a 11 Live View 17 pages 17 rich text comments 16 Rich Text Comments 16 Playground editor 12 PlaygroundPage 18 PlaygroundSupport module 17 Playground Timelines 14 preferred text size 138 Preview Canvas 110 Preview on Device 112, 113 Preview Pinning 112 PreviewProvider protocol 117 Profile in Instruments 123 ProgressView 305 circular 305, 306 CircularProgressViewStyle 306 customization 307 indeterminate 305, 307 linear 305, 306 makeBody() 307, 308 progressViewStyle() 307 ProgressViewStyle 307 styles 305 progressViewStyle() 307 ProgressViewStyle 307 Property Wrappers 83 example 83 Multiple Variables and Types 85 Protocols 68 published properties 160 R Range Operators 35 Rectangle() 277 Reference Types 78 repeatCount() modifier 289 repeatForever() modifier 289 repeat while loop 42 requestSiriAuthorization() 334 Resume button 111 Right Shift Operator 39 Rotation 170 running an app 119 S scale 294 Scene 127 SceneStorage 191 ScrollView 151, 261 Segue Action 447 self 67 setVocabularyStrings(oftype:) 331 SF Symbols 143 macOS app 143 Shapes 280 drawing 277 Shared folder 129 Shortcut Types 372 shorthand argument names 59, 91, 173 SidebarListSyle 250 sign bit 39 Signing Identities 9 Simulator running app 119 Simulators managing 121 Siri 327 enabling entitlement 347, 367 Siri Authorization 348, 367 SiriKit 327 configure() method 339 configureView() method 343, 344 confirm method 330 custom user interfaces 339 custom vocabulary 331 domains 327 handle method 330 intent handler 328 intents 328 overview 328 Photo Search tutorial 347 resolving intent parameters 329 Snippet 341 UI Extension 328, 339 SiriKit Intent Definition file 361 SiriKit Intent Definition File Configuring 370 Siri Shortcuts 328, 361 Adding Intent Parameters 371 Adding the Intents Extension 368 Add to Siri Button 364 Custom Intents 363 declaring shortcut types 372 donating 361, 364, 378 Intent Response 373 overview of 361 response templates 363 Shortcut Types 363 testing 379 tutorial 365 Siri Snippet 339, 341 slide 294 Slider view 168 some keyword 69 source code download 1 Spacers 147 Spacer view 175 Spacer View 147 spring() modifier 289 Stack embed views in a 167 Stacks 145 alignment 199 alignment guides 199 child limit 149 cross stack alignment 208 implicit alignment 199 Layout Priority 150 State Binding 159 State Objects 161 State properties 157 binding 158 example 168 StaticConfiguration 387 Stored and Computed Properties 65 stored properties 65 String data type 23 stroke() modifier 278 StrokeStyle 278 struct keyword 77 Structures 77 subheadline 138 subtraction operator 33 Subviews 136 Swift Arithmetic Operators 33 array interation 91 arrays 89 Assignment Operator 33 base class 71 Binary Operators 34 Bitwise AND 37 Bitwise Left Shift 38 Bitwise NOT 37 Bitwise Operators 37 Bitwise OR 38 Bitwise Right Shift 39 Bitwise XOR 38 Bool 23 Boolean Logical Operators 35 break statement 43 calling a function 52 case statement 47 character data type 23 child class 71 class declaration 61 class deinitialization 63 class extensions 74 class hierarchy 71 class initialization 63 Class Methods 62 class properties 61 closed range operator 35 Closure Expressions 58 Closures 59 Comparison Operators 34 Compound Assignment Operators 34 Compound Bitwise Operators 39 constant declaration 25 constants 25 continue statement 43 control flow 41 data types 21 Dictionaries 92 while loop 42 error handling 97 Escape Sequences 24 exclusive OR 38 expressions 33 floating point 22 for Statement 41 function declaration 51 functions 51 guard statement 45 half-closed range operator 36 if else … Statements 44 if Statement 44 implicit returns 1, 21, 52 Inheritance, Classes and Subclasses 71 Instance Properties 62 instance variables 62 integers 22 methods 61 opaque return types 69 operators 33 optional binding 28 optional type 27 Overriding 72 parent class 71 Property Wrappers 83 protocols 68 Range Operators 35 Reference Types 78 root class 71 single expression functions 52 single expression returns 52 single inheritance 71 Special Characters 24 Stored and Computed Properties 65 String data type 23 structures 77 subclass 71 switch fallthrough 50 switch statement 47 syntax 47 Ternary Operator 36 tuples 26 type annotations 25 type casting 30 type checking 30 type inference 25 Value Types 78 variable declaration 25 variables 25 while loop 42 Swift Playground 11 Swift Structures 77 SwiftUI create project 107 custom views 133 data driven 104 Declarative Syntax 103 example project 165 overview 103 Subviews 136 Views 133 SwiftUI Project anatomy of 129 creating 107 SwiftUI Views 133 SwiftUI View template 185 SwiftUI vs UIKit 104 switch statement 47 example 47 switch Statement 47 example 47 range matching 49 T Tabbed Views 269 tabItem() 271 Tab Items 271 Tab Item Tags 271 TabView 269 PageTabViewStyle() 270 page view style 270 tab items 271 tag() 271 ternary operator 36 TextField view 171 Text Styles 138 Text view adding modifiers 169 line limits 150 throw statement 98 timeline entries 386 TimelineEntryRelevance 389 timeline() method 402 TimelineProvider 388 ToggleButton view 158 transition() modifier 294 Transitions 287, 293 asymmetrical 295 combining 295 move(edge\ edge) 294 opacity 294 scale 294 slide 294 try statement 98 try! statement 100 Tuple 26 Type Annotations 25 type casting 30 Type Checking 30 Type Identifiers 313 Type Inference 25 type safe programming 25 U UIHostingController 443 UIImagePickerController 435 UIKit 103 UIKit integration data sources 430 delegates 430 UIKit Integration 427 Coordinator 429 UInt8 22 UInt16 22 UInt32 22 UInt64 22 UIRefreshControl 429 UIScrolledView 430 UIView 427 SwiftUI integration 427 UIViewController 435 SwiftUI integration 435 UIViewControllerRepresentable protocol 435 UIViewRepresentable protocol 429 makeCoordinator() 429 unary negative operator 33 Unicode scalar 25 Uniform Type Identifier 313 upcasting 30 updateView() 428 UserDefaults 192, 365 UTI 313 UTType 316 UUID() method 216 V Value Types 78 variables 25 variadic parameters 54 VerticalAlignment 204, 205 View 128 ViewBuilder 142 ViewDimensions 206 ViewDimensions object 203 View Hierarchy exploring the 123 ViewModifier protocol 140 Views adding 185 as properties 136 modifying 137 VStack 134, 145 adding to layout 167 W where clause 29 where statement 49 while Loop 42 WidgetCenter 389 Widget Configuration 385 WidgetConfiguration 385 WidgetConfiguration protocol 385 Widget Configuration Types 386 Widget Entry View 385, 387 Widget Extension 385 widgetFamily 408, 412 Widget kind 385 WidgetKit 407, 413, 419 configurable widgets 419 ConfigurationIntent 420 Configuration Intent UI 425 Deep Links 413, 416 Intent Configuration 385, 386 IntentConfiguration 387 Intent Definition File 419 IntentTimelineProvider 402 introduction 385 Reload Policy 388 ReloadPolicy after(Date) 389 atEnd 389 never 389 size families 407 snapshot() 388 Static Configuration 385, 386 StaticConfiguration 387 timeline() 388 timeline entries 386 TimelineEntryRelevance 389 timeline example 398 timeline() method 402 Timeline Reload 389 tutorial 393 Widget Configuration 385 WidgetConfiguration protocol 385 widget entry view 401 Widget Entry View 385, 387 Widget Extension 385, 395 widgetFamily 408, 412 widget gallery 410 Widget kind 385 Widget Provider 388, 402 Widget Sizes 390 widget timeline 386 Widget Provider 388 Widget Sizes 390 widget timeline 386 widgetUrl() 415 WindowGroup 128, 130 withAnimation() closure 290 X Xcode account configuration 8 Attributes inspector 116 code editor 109 create project 107 debug panel 109 installation 7 Library panel 114 Live Preview 112 preferences 8 preview canvas 110 Preview on Device 113 Preview Resume button 111 project navigation panel 109 starting 107 SwiftUI mode 107 system requirements 7 XOR operator 38 Z ZStack 145, 199 alignment 210 ZStack Custom Alignment 210 .. .SwiftUI Essentials iOS 14 Edition SwiftUI Essentials – iOS 14 Edition ISBN-13: 97 8-1 -9 5144 2-2 7-9 © 2020 Neil Smyth / Payload Media, Inc All Rights Reserved... Commonly used special characters supported by Swift are as follows: • - New line • - Carriage return • - Horizontal tab •\ - Backslash •” - Double quote (used when placing a double quote into a string declaration) •’ - Single quote (used when placing a single quote into a string declaration)... 14. 3.2 Accessing Array Items 14. 4 Random Items and Shuffling 14. 5 Appending Items to an Array 14. 5.1 Inserting and Deleting Array Items 14. 6 Array Iteration 14. 7 Creating Mixed Type Arrays 14. 8 Swift Dictionary Collections