Explore 1.5M+ audiobooks & ebooks free for days

From $11.99/month after trial. Cancel anytime.

An iOS Developer's Guide to SwiftUI: Design and build beautiful apps quickly and easily with minimum code
An iOS Developer's Guide to SwiftUI: Design and build beautiful apps quickly and easily with minimum code
An iOS Developer's Guide to SwiftUI: Design and build beautiful apps quickly and easily with minimum code
Ebook916 pages5 hours

An iOS Developer's Guide to SwiftUI: Design and build beautiful apps quickly and easily with minimum code

Rating: 0 out of 5 stars

()

Read preview
LanguageEnglish
PublisherPackt Publishing
Release dateMay 3, 2024
ISBN9781801817912
An iOS Developer's Guide to SwiftUI: Design and build beautiful apps quickly and easily with minimum code
Author

Michele Fadda

Michele Fadda, an Italian software developer with over 30 years of experience working in the UK. He began programming at 14. He has worked across telematics, medical, banking, and financial sectors, specializing in iOS and Swift. Michele has contributed to various projects, including medical device apps, telematics apps and financial systems. He pioneered electronic controls for automotive trucks, began his career with aerospace projects and led a MIL-STD qualified helicopter maintenance project. Michele's expertise includes cryptography and system architecture design. He holds an MBA and authored "An iOS Developer's Guide to SwiftUI." Currently, he is the CEO of FWLAB Limited in the UK, focusing on bespoke mobile development and AI.

Related to An iOS Developer's Guide to SwiftUI

Related ebooks

Operating Systems For You

View More

Reviews for An iOS Developer's Guide to SwiftUI

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    An iOS Developer's Guide to SwiftUI - Michele Fadda

    Cover.png

    An iOS Developer’s Guide to SwiftUI

    Copyright © 2024 Packt Publishing

    All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

    Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

    Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

    Group Product Manager: Rohit Rajkumar

    Publishing Product Manager: Vaideeshwari Muralikrishnan

    Book Project Manager: Aishwarya Mohan

    Senior Editor: Rakhi Patel

    Technical Editor: Reenish Kulshrestha

    Copy Editor: Safis Editing

    Indexer: Pratik Shirodkar

    Production Designer: Prafulla Nikalje

    DevRel Marketing Coordinators: Anamika Singh and Nivedita Pandey

    First published: May 2024

    Production reference: 1050424

    Published by Packt Publishing Ltd. Grosvenor House 11 St Paul’s Square Birmingham B3 1RB, UK

    ISBN 978-1-80181-362-4

    www.packtpub.com

    Dedicated to my love, Stefania.

    – Michele Giuseppe Fadda

    Contributors

    About the author

    Michele Fadda is an Italian software developer with over 30 years of expertise in a range of sectors, including banking, healthcare, and open banking. He began his programming journey at 14 in Sassari and relocated to Milan in 1983, where he started his career in embedded systems software, later expanding into enterprise and mobile software development. Michele also contributed as a tech journalist from 1983 to 1997, focusing on digital electronics and programming. He is fluent in both Italian and English and holds an MBA from the Open University Business School, along with a diploma in business studies.

    With a deep understanding of computing history, Michele has been at the forefront of software development since the Unix System V era. He has led IT projects for numerous Italian companies, mastering a variety of programming languages and, lately, specializing in iOS and Swift for mobile applications. Michele is particularly interested in cryptography and designing secure systems.

    In addition to his professional achievements, Michele has a passion for electronic music, blending his technological expertise with a creative flair for sound. Since 2018, he has been working in the UK, working as an iOS developer. He is currently the CEO of FWLAB Limited and technical project and program manager at Eggon, an innovative Italian start-up.

    I want to thank the Packt team and reviewers who helped me through this journey and made this book possible.

    About the reviewer

    Nimesh Neema is a passionate programmer who loves well-designed software. He is proficient with Apple developer technologies and has written apps for the iPhone, iPad, Mac, Apple Watch, and Apple TV. He has an excellent understanding of shell scripting, version control, and software engineering principles.

    In a career spanning over 15 years, he has worked with teams of diverse sizes and backgrounds. He has experience writing utility, payment, gaming, hospitality, and low-level system apps.

    He runs a software engineering consultancy, Perspicacious Solutions Private Limited, with clients from around the world. He engages in corporate training and speaking gigs. He is one of the highly-rated Apple development experts on codementor.io

    .

    Table of Contents

    Preface

    Part 1: Simple Views

    1

    Exploring the Environment – Xcode, Playgrounds, and SwiftUI

    Technical requirements

    Exploring SwiftUI with Xcode

    A brief tour of Xcode

    Your first SwiftUI project

    Creating a SwiftUI project

    Creating a multi-platform project

    Previews and the simulator

    Playgrounds

    The app submission process

    Certificates

    Mobile provisioning profiles

    The application submission process

    Summary

    2

    Adding Basic UI Elements and Designing Layouts

    Technical requirements

    Reusing views code

    More about Text

    Managing space in SwiftUI

    The padding modifier

    The .frame modifier

    The .alignment modifier

    The Spacer

    The Divider

    Digging deeper into stacks

    Overview of stacks

    HStack

    ZStack

    Summary

    3

    Adding Interactivity to a SwiftUI View

    Technical requirements

    Passing values at view creation

    Responding to a button tap

    Property wrappers

    Limitations of @State

    Changing a view appearance dynamically using modifiers

    Bidirectional binding with Picker

    Final notes on Subviews and @Binding, Classes, and @ObservableObject

    Summary

    Part 2: Scrollable Views

    4

    Iterating Views, Scroll Views, FocusState, Lists, and Scroll View Reader

    Technical requirements

    Iterating views

    Hiding or showing the keyboard in a form using @FocusState

    Scroll views

    Controlling scrolling programmatically using ScrollViewReader

    Summary

    5

    The Art of Displaying Grids

    Technical requirements

    Displaying grids in iOS

    The Grid view

    Creating a simple static grid

    Lazy grids

    Using GridItem to control the layout of LazyVGrid

    Scrolling horizontally and sizing the grid automatically

    Conditional formatting of a view

    Reacting to device rotation

    Summary

    Part 3: SwiftUI Navigation

    6

    Tab Bars and Modal View Presentation

    Technical requirements

    Creating a standard tab bar

    Creating custom tab bars

    Adapting your code to different versions of the operating system

    The hitchhiker’s guide to modal navigation

    Showing a modal sheet

    Showing alerts

    The popover

    Presentation detents

    Summary

    7

    All About Navigation

    Technical requirements

    Navigation as a concept in iOS and other platforms

    Showing a tab bar title with NavigationView

    Presenting views with NavigationLink (pre-iOS 16)

    Adding buttons to NavigationView and activating navigation programmatically

    Using navigationDestination with NavigationStack

    Using NavigationPath to control the navigation stack

    NavigationSplitView – multicolumn navigation

    Direct navigation stack manipulation with NavigationPath

    Saving and loading the navigation stack

    Summary

    Part 4: Graphics and Animation

    8

    Creating Custom Graphics

    Technical requirements

    Creating custom modifiers

    Drawing with the Canvas

    Using CALayers in SwiftUI

    Custom layout

    Summary

    9

    An Introduction to Animations in SwiftUI

    Technical requirements

    Gestures

    Basic gestures

    Creating implicit animations

    Explicit SwiftUI animations

    Transitions

    The .transition() modifier

    The matchedGeometryEffect modifier

    Summary

    Part 5: App Architecture

    10

    App Architecture and SwiftUI Part I: Practical Tools

    Diagrams

    Dependency inversion

    Clean Architecture

    Different ways to decouple

    Initializer injection

    Method injection

    Property injection

    A matter of state

    iOS 17 changes in state management

    Other ways to chop your code

    Summary

    11

    App Architecture and SwiftUI Part II – the Theory

    Keeping it light enough

    Conflict and the role of the architect

    What good software architecture is and what it is not

    Don’t be shy; ask an expert!

    The origin of software patterns

    Agency theory and bad architecture

    Clean Architecture

    TCA, The Composable Architecture

    Summary

    Part 6: Beyond Basics

    12

    Persistence with Core Data

    What is persistency?

    What is Core Data?

    Understanding Core Data framework classes

    Using Core Data with SwiftUI

    Creating a Core Data project

    Working with the data model file

    Core Data migrations

    The SQLite data file

    CloudKit

    Summary

    13

    Modern Structured Concurrency

    A brief introduction to concurrency

    Understanding traditional concurrency mechanisms

    Threads

    Callbacks and event loops

    GCD

    What is structured concurrency?

    Using the async/await syntax

    Understanding tasks

    Task groups

    Asynchronous streams

    Actors

    MainActor

    Bridging old GCD and structured concurrency

    Summary

    14

    An Introduction to SwiftData

    Technical requirements

    Understanding the differences between SwiftData and Core Data

    SwiftData and SwiftUI

    Exploring changes in the binding mechanisms

    Creating a data model

    Understanding relationships in SwiftData

    One-to-one relationships

    One-to-many relationships

    Many-to-one relationships

    Many-to-many relationships

    Cascading deletion rules

    Fetching data

    Filtering data with predicates

    Summary

    15

    Consuming REST Services in SwiftUI

    Technical requirements

    An overview of REST

    Ports

    Understanding REST requests in Swift

    Codable, Encodable, and Decodable protocols

    Using URLSession

    Implementing HTTP methods

    Setting headers

    Handling errors

    URLProtocol

    Summary

    16

    Exploring the Apple Vision Pro

    Technical requirements

    Tools for visionOS development

    An overview of Unity and RealityKit

    First steps with visionOS development

    Summary

    Index

    Other Books You May Enjoy

    Preface

    This book teaches you about SwiftUI, a multiplatform declarative user interface framework that can be used to program all Apple devices, currently including Mac, iPhone, iPad, Apple TV, Apple Watch, and Vision Pro.

    Who this book is for

    This book is aimed at iOS developers who want to expand their knowledge of adding SwiftUI to their bag of tools and want to progress further in their professional careers.

    What this book covers

    Chapter 1

    , Exploring the Environment – Xcode, Playgrounds, and SwiftUI, is an introduction to the software tools used when working with SwiftUI, the new exciting, efficient, and simple-to-use Apple framework for user interfaces.

    Chapter 2

    , Adding Basic UI Elements and Designing Layouts, shows you how to properly refactor view code. Then, it describes how to combine basic views with stacks and control their visual layout.

    Chapter 3

    , Adding Interactivity to a SwiftUI View, discusses the conversion from static to dynamic SwiftUI views, with a focus on responsive design, including taps and gestures. This chapter explores mechanisms to enable views to be made interactive. It covers topics such as view creation, interactivity enhancement, property wrappers, limitations of @State, bidirectional bindings, subviews, and the use of @ObservableObject and @StateObject classes.

    Chapter 4

    , Iterating Views, Scroll Views, FocusState, Lists, and Scroll View Reader, focuses on showing lists in SwiftUI, through scrollable views such as scroll views or lists. It shows how to handle the visibility of the iOS system keyboard. It introduces NavigationView for view titles and covers iterating views, @ViewBuilder, scroll views, @FocusState for keyboard control, lists, and ScrollViewReader for element positioning within lists or scroll views.

    Chapter 5

    , The Art of Displaying Grids, moves on to creating grid structures in SwiftUI. Topics covered include displaying grids in iOS, the grid view, lazy grids, using GridItem for layout control, conditional view formatting, and responding design to device orientation changes.

    Chapter 6

    , Tab Bars and Modal View Presentation, focuses on using tab bars and modal view presentations in SwiftUI. It begins with the TabView, which is the most common way of moving between views in a small-scale iOS app. Topics covered include how to add a tab bar using TabView and tabItem, implementing custom tab bars, and an exhaustive investigation into modal views such as sheets, alerts, and popovers.

    Chapter 7

    , All About Navigation, introduces the concept of navigation in SwiftUI. It starts with an overview of iOS navigation and then deals with programmatic and user-initiated navigation. It illustrates the changes with Swift 4 and iOS 16. Topics discussed are navigation across platforms, basic navigation with NavigationView and NavigationLink, .navigationDestination, user-controlled and split view navigation, programmatic navigation with NavigationPath, and saving/restoring the navigation stack in the JSON format.

    Chapter 8

    , Creating Custom Graphics, shows you how to style apps by creating custom modifiers, diving into the use of core graphics inside the Canvas view, CALayers integration with SwiftUI. Then, the chapter goes further, illustrating how to use CustomLayout.

    Chapter 9

    , An Introduction to Animations in SwiftUI, highlights SwiftUI animations, explaining their state-driven, reactive nature, made possible by SwiftUI’s declarative syntax. It explains the built-in modifiers of animation, transition, and scaleEffect.

    Chapter 10

    , App Architecture and SwiftUI Part I – the Practical Tools, dissects the impact that SwiftUI has had in restructuring the application architecture on Apple’s operating systems. It introduces conceptual tools that allow a developer to segment an app into manageable components. This chapter focuses on ad hoc architecture rather than offering a one-size-fits-all solution. Key topics include diagrams, dependency inversion, clean architecture, decoupling techniques, state management, and iOS 17 changes on state bindings.

    Chapter 11

    , App Architecture and SwiftUI Part II – the Theory, introduces modern application architecture, taking note of the specificity of the iOS context. It explains the concept of software architecture to give a theoretical understanding and criteria for evaluating well-designed architecture. Key topics include the principles of lightweight architecture, conflict resolution, defining good architecture, the importance of software patterns, the role of the architect, consulting experts, the difference between full-scale applications and examples, and the impact of Conway’s law.

    Chapter 12

    , Persistence with Core Data, focuses on defining persistence, explaining Core Data’s structure, its integration with SwiftUI, and its practical use in Xcode. It touches on CloudKit for cloud-based data storage. Key topics include the Core Data’s framework classes, Core Data with SwiftUI, project creation and migrations, the SQLite data file, and CloudKit.

    Chapter 13

    , Modern Structured Concurrency, discusses concurrency in mobile application development nowadays, applied specifically to Swift. The chapter outlines the history of concurrency from traditional mechanisms, such as threads and callbacks, to Apple’s modern structured concurrency approach. Its topics include async/await, tasks, task groups, asynchronous sequences and streams, actors, and integrating old-fashioned concurrency with modern structured concurrency.

    Chapter 14

    , An Introduction to SwiftData, describes Apple’s ORM (Object Relational Mapping) framework, SwiftData, which is set to replace Core Data in SwiftUI development. The topics covered include SwiftData versus Core Data, SwiftData’s features, SwiftUI integration, data modeling, and the changes in binding.

    Chapter 15

    , Consuming REST services in SwiftUI, explains HTTP, and REST as concepts and how to integrate REST services into SwiftUI applications for iOS apps that demand communication over the internet. Topics covered include HTTP requests made using URLSession, converting to and from JSON using Codable, watching UI changes with ObservableObject and @Published, avoiding man-in-the-middle attacks, and handling network errors.

    Chapter 16

    , Exploring the Apple Vision Pro, introduces Apple Vision Pro, an advanced mixed-reality headset, and its importance for spatial computing. It describes the device’s immersive three-dimensional interface. It also goes into the development tools for visionOS, starting development with visionOS, and the initial steps in visionOS development.

    To get the most out of this book

    It is assumed that you will be familiar with basic computer science and programming in the Swift programming language on Apple devices.

    If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

    You will need a developer’s account only if you want to use physical devices. Xcode can be downloaded for free from the Mac App Store and won’t require a developer’s account in order to run your own applications on the simulator.

    Download the example code files

    You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/An-iOS-Developer-s-Guide-to-SwiftUI

    . If there’s an update to the code, it will be updated in the GitHub repository.

    We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/

    . Check them out!

    Conventions used

    There are a number of text conventions used throughout this book.

    Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: In order to create explicit animations, you use the .animation(_: value:) modifier rather than the simpler .withAnimation closure.

    A block of code is set as follows:

    // if you are using Xcode 14.x you will need this syntax for the preview functionality:

    struct ContentView_Previews: PreviewProvider {

        static var previews: some View {

            ContentView()

        }

    When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

    [default]

    // if you are using Xcode 15 or later, the preview can be simplified as follows:

    #Preview {   ContentView() }

    Any command-line input or output is written as follows:

    $ cd projectFolder

    $ open .

    Bold: Indicates a new term, an important word, or words that you see on screen. For instance, words in menus or dialog boxes appear in bold. Here is an example: Select Settings from the Xcode menu.

    Tips or important notes

    Appear like this.

    Get in touch

    Feedback from our readers is always welcome.

    General feedback: If you have questions about any aspect of this book, email us at [email protected]

    and mention the book title in the subject of your message.

    Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata

    and fill in the form.

    Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected]

    with a link to the material.

    If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com

    .

    Share Your Thoughts

    Once you’ve read An iOS Developer’s Guide to SwiftUI, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page

    for this book and share your feedback.

    Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.

    Download a free PDF copy of this book

    Thanks for purchasing this book!

    Do you like to read on the go but are unable to carry your print books everywhere?

    Is your e-book purchase not compatible with the device of your choice?

    Don’t worry!, Now with every Packt book, you get a DRM-free PDF version of that book at no cost.

    Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.

    The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily

    Follow these simple steps to get the benefits:

    Scan the QR code or visit the following link:

    https://packt.link/free-ebook/9781801813624

    Submit your proof of purchase.

    That’s it! We’ll send your free PDF and other benefits to your email directly.

    Part 1: Simple Views

    In this part, you will be introduced to SwiftUI, the multiplatform UI framework from Apple that allows developers to build user interfaces for all Apple devices. These chapters have been designed for iOS developers in such a way that they guide you through the main concepts of SwiftUI and its practical implementation, offering a concrete base to develop powerful and visually beautiful applications.

    You will start to explore the fundamentals of SwiftUI and its declarative syntax to build an intuitive and efficient UI. We’ll cover key concepts, such as views, modifiers, and state management, demonstrating how these components work together to build dynamic layouts.

    You will learn to manage data well within SwiftUI, ensuring slick, dynamic user interfaces are produced through bindings, observable objects, and environment values.

    This part will teach you how to work with animation and the gesture features of SwiftUI by applying them with a layer of polish and interactivity to your apps. You should reach the end of this section prepared with the knowledge and skills needed to begin using SwiftUI for your iOS development projects, making applications that are not only functional but also visually engaging.

    This part contains the following chapters:

    Chapter 1

    , Exploring the Environment – Xcode, Playgrounds, and SwiftUI

    Chapter 2

    , Adding Basic UI Elements and Designing Layouts

    Chapter 3

    , Adding Interactivity to a SwiftUI View

    1

    Exploring the Environment – Xcode, Playgrounds, and SwiftUI

    This chapter is an introduction to the tools used when working with SwiftUI, the new, exciting, efficient, and simple-to-use Apple framework for user interfaces (UIs). We’re going to cover the following main topics in this chapter:

    Exploring Xcode and SwiftUI

    Creating a multi-platform SwiftUI project

    Using Swift Playgrounds to test fragments of code

    Adding tests

    The App submission process

    By the end of this chapter, you will learn how to create a project from scratch. You will also learn how to create a project using the project templates and how to add tests and preview your SwiftUI views code.

    Note

    The opinions expressed in this book are solely those of the author and do not necessarily reflect the views or policies of his employers or other entities. Any reference to organizations, events, or individuals is purely fictional and intended for illustrative purposes only. Resemblance to any existing companies, events, or persons, living or deceased, is purely coincidental unless the specific name of an individual is mentioned.

    Technical requirements

    You will require a recent Apple computer to run the examples and code in this book. In general, the more RAM and more powerful your system, the better. This book has been tested on an Intel MacBook Pro running macOS 13.6 (Ventura) with 16 GB of RAM. It will work just as fine on a more recent Apple Silicon machine.

    To follow this chapter and the rest of the book, you will be required to install Xcode version 15.0 or later.

    If you want to run code on a physical device with Xcode 15.0, you will be able to use the async/await pattern in concurrent programming for devices running at least iOS 13. We suggest updating your device to iOS 17 or later to follow this book.

    The complete projects and code samples for the examples discussed in the book can be found under the GitHub repository: https://github.com/PacktPublishing/An-iOS-Developer-s-Guide-to-SwiftUI

    .

    Exploring SwiftUI with Xcode

    In this section, we are going to look into the Xcode UI in the context of a SwiftUI project.

    Xcode is quite a large topic by itself. We will focus on SwiftUI and explain enough about how Xcode usage differs in SwiftUI from UIKit to get you started, how to create a SwiftUI project, and add targets for various Apple platforms. Also, we will explain how to add tests to a project.

    A brief tour of Xcode

    Xcode is an integrated development environment (IDE) for developing any code on any device that Apple produces. Xcode is therefore a massive and complex app capable of supporting many different types of projects and technologies. Not all of these types of projects are relevant to SwiftUI, so we will limit ourselves to Swift as a language and SwiftUI as a UI framework. In the past, the only supported language for app development was Objective-C and the only supported UI framework was different for each device platform, notably UIKit for iOS and AppKit for macOS. Swift was introduced at a later stage, but before SwiftUI, the core architecture of the UI layer for Apple apps did not change, and actually, most of it was still dependent on frameworks developed internally in Objective-C. SwiftUI is the first pure Swift approach to UIs. We will focus on Swift and SwiftUI.

    You can install Xcode from the Mac App Store, or if you have an Apple Developer account, you can choose to download a particular version of it from the download section of your developer account. It is a hefty download; it will take a while unless you have a high-speed internet connection.

    After downloading and installing it, you will be asked to download additional components; permit it by clicking Install:

    Figure 1.1 – Installing the additional Xcode components

    Figure 1.1 – Installing the additional Xcode components

    Installing Xcode from the Mac App Store is the easiest way to get the most recent stable version. If you want to install a beta version or a previous specific version, you can download it from your developer’s account download area. It will download an archived file with a .xip extension. Double-clicking on it will expand the archive to give the Xcode.app bundle. You might want to rename it if you’re using different versions of Xcode on the same machine.

    You may also want to install the current version from a .xip file if you don’t have a good internet connection in order to overcome installation difficulties. However, please don’t install multiple versions of Xcode unless you have an excellent reason to do it, as this might cause you some additional problems. When you open a project with an older version of Xcode, this might cause some obscure bugs when you forget to select the appropriate version of the command-line tools.

    Luckily, with SwiftUI, several incompatibilities and difficult-to-diagnose bugs due to the corruption or slight incompatibilities among storyboard files are gone as you won’t be working with storyboard files anymore, and the representation of views is done with declarative Swift code; it is just human-readable plain text. These problems and the difficulties of merging storyboard files, which were never intended to be edited by hand with a text editor, were particularly relevant when using storyboards in large teams, to the point that many development teams chose to give up on storyboard and resorted to programming views in code in UIKit for this precise reason.

    It is advisable to install Xcode in the Applications folder for everyday use, like any regular app.

    The Applications folder is where Xcode is usually installed when you download it from the App Store. In rare cases where you want to have more than one version of Xcode on the same machine, you might want to install some of the other versions in other folders (e.g., the Desktop folder).

    Bear in mind that Apple keeps on adding features and project templates for various coding artifacts, so feel free to experiment and learn what different project creation options do.

    If you want to delete a project, close Xcode, delete the project folder by dragging it to the bin, and reopen Xcode. Be warned that due to a bug in some versions of Xcode, such as 13.2, it might recreate an empty project if you delete the only existing recently created project.

    You could also structure your project using workspaces, which could contain one or more interdependent projects. For the time being, stick to using a single Xcode project rather than an Xcode workspace unless you have a reason; for example, wanting to use a third-party package manager that requires you explicitly to use workspaces.

    Xcode has a relatively extensive menu (on the top of the screen). Please familiarize yourself with it and use the Help menu item to read the developer documentation whenever you have a doubt or want to learn more about its functionality.

    Xcode defaults with Xcode 15 are pretty good the way they are; for instance, you won’t need to set it to display line numbers, as that is the default behavior.

    You might want to change the Xcode default editor theme to something of your liking; some developers prefer to work with light text on a dark background. You can choose that by selecting the desired theme under the Themes tab in Xcode Preferences. I usually like the default white background as I feel that it is easier on the eyes, but it is a matter of personal preference. It would help if you personalized your editor in a way that suits you.

    You will need to add your Apple Developer account under Preferences | Accounts if you have one. This will automatically allow Xcode to deal with your application certificates, which is the easiest way to work alone on your apps.

    To be sure that the command-line interface for Xcode has been installed correctly, you should run the following command:

    xcode-select –install

    If you see a prompt asking you to accept the Xcode license agreement, accept it.

    Also, Xcode may occasionally ask for your permission to access a folder or to perform a certain action; this will typically require your user password. You are normally supposed to be the administrator of your own machine in order to be able to develop with Xcode.

    When you run Xcode, you will see a dialogue showing projects and playgrounds you have accessed recently if any along with the Create New Project..., Clone Git Repository..., and Open Existing Project...:

    Figure 1.2 – Initial Xcode screen and menu

    Figure 1.2 – Initial Xcode screen and menu

    Now that we have gone through some basic information about Xcode, we will move on to the next section where we will see how a SwiftUI app starts in Xcode.

    How the app starts

    To get started, clone or download this book’s project files from GitHub (the link to the GitHub repository is mentioned in the Technical requirements section), navigate to the CH1 | Ch1FirstProject folder, and open the project file named Ch1FirstProject.xcodeproj.

    Once you open the project, you will notice that the AppDelegate project file has been replaced by an App file, which now contains just a struct implementing the App protocol and is marked with @main, signifying that it is the main entry point for the code execution of the app.

    This struct creates WindowGroup from ContentView. According to the Apple documentation, WindowGroup is a container for your app’s view hierarchy. It adapts to the supported platform supporting its peculiar capabilities (e.g., supporting more than one window (for iPadOS and macOS)). The WindowGroup supports the main app UI interface, except for document apps which require DocumentGroup instead.

    The following screenshot shows the main Xcode UI:

    Figure 1.3 – Locating the App file in a project

    Figure 1.3 – Locating the App file in a project

    The following code segment shows the SwiftUI equivalent of the old AppDelegate:

    import SwiftUI

    @main

    struct Ch1FirstProjectApp: App {

        var body: some Scene {

            WindowGroup {

                ContentView()

            }

        }

    }

    This is what developers normally refer to

    Enjoying the preview?
    Page 1 of 1