Explore 1.5M+ audiobooks & ebooks free for days

From $11.99/month after trial. Cancel anytime.

iOS Development with SwiftUI: Acquire the Knowledge and Skills to Create iOS Applications Using SwiftUI, Xcode 13, and UIKit
iOS Development with SwiftUI: Acquire the Knowledge and Skills to Create iOS Applications Using SwiftUI, Xcode 13, and UIKit
iOS Development with SwiftUI: Acquire the Knowledge and Skills to Create iOS Applications Using SwiftUI, Xcode 13, and UIKit
Ebook764 pages3 hours

iOS Development with SwiftUI: Acquire the Knowledge and Skills to Create iOS Applications Using SwiftUI, Xcode 13, and UIKit

Rating: 0 out of 5 stars

()

Read preview

About this ebook

‘iOS Development with SwiftUI' focuses on teaching and practicing the use of SwiftUI for developing iOS applications that leverage the latest iOS features.

To begin, the book covers the fundamentals of SwiftUI and its core functionalities and how to write UI without having to worry much about it. It explains the fundamental Swift syntax, data types, control statements, functions, classes, and structures, as well as methods, protocols, and closures. The book covers expert tips for adding animations with a single line of code, as well as some SwiftUI transitions. Then, through a dissection of an iOS application, it teaches how to create APIs and implement API calls. It also covers widgets, App Clip development, web banner creation, and how the app communicates with the App Clip.

The book will help demonstrate how to integrate XCTest into your application for both UI and unit testing and how to write your test case and prepare the application for general use.

At the end of the book, you will be able to write an iOS application in SwiftUI and gain some experience to call API or web services using combine.
LanguageEnglish
PublisherBPB Online LLP
Release dateJan 13, 2022
ISBN9789391030995
iOS Development with SwiftUI: Acquire the Knowledge and Skills to Create iOS Applications Using SwiftUI, Xcode 13, and UIKit
Author

Mukesh Sharma

Dr. Mukesh Sharma is currently a Research Fellow at Department of Chemical Engineering, Indian Institute of Technology Guwahati (IITG), India. He obtained his M.Sc. and PhD in Earth Science and Technology from Indian Institute of Technology Kharagpur, West Bengal, India. His research work includes membrane technology and its applications in simultaneous sustainable energy extraction, electrochemistry, wastewater treatment, water treatment, bioelectrochemical process, desalination, waste management, resource recovery, fuel cells and formation of value-added products derived from agricultural wastes and processes intensification. He has published many scientific research and review papers in various reputed international journals. He has authored several book chapters in various publications, including Elsevier, CRC and Springer and patented technologies and its demonstrations on the field of blue energy generations.

Related to iOS Development with SwiftUI

Related ebooks

Computers For You

View More

Reviews for iOS Development with 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

    iOS Development with SwiftUI - Mukesh Sharma

    CHAPTER 1

    What is SwiftUI?

    Introduction

    In this chapter, we will give you a detailed introduction to Apple’s newest app development framework SwiftUI, after a few general words about SwiftUI, will review its architecture.

    WWDC is always a source of exciting stuff for developers; everyone waits with bated breath to see what new tech is being introduced by Apple. The most recent pioneering piece of tech released by Apple was in 2014 when Apple released Swift in addition to Apple’s currently used programming language, Objective-C. Since its release, Swift has updated and evolved, eventually becoming one of today’s most beloved and powerful programming languages.

    SwiftUI was announced by Apple at WWDC19 and is described as SwiftUI is an innovative, exceptionally simple way to build user interfaces across all Apple platforms with the power of Swift and that’s true with SwiftUI; it’s surprisingly simple to build apps just like you imagine them to look.

    Structure

    This chapter covers the details of SwiftUI:

    Introduction to SwiftUI

    The SwiftUI architecture

    Opaque types

    SwiftUI for all Apple products

    Objective

    The objective of this chapter is to explain SwiftUI, SwiftUI architecture, and technical requirements to run the SwiftUI on macOS. For this book, our focus is on developing iOS applications for the iPhone.

    SwiftUI follows a declarative syntax approach, meaning that we depict in code how our interface should look:

    Figure 1.1: SwiftUI example with preview

    Technical requirements for running SwiftUI

    SwiftUI shipped with Xcode 11, which you can download for free from the Mac App Store. Note that SwiftUI is only compatible with running at least macOS Catalina and BigSur or later versions.

    When you start creating your project with Xcode 13, you have to select an alternative to storyboard, select the SwiftUI from the dropdown, as seen in the following screenshot:

    Figure 1.2: Showing selection option for SwiftUI

    This approach to app creation is a true cross-Apple platform and, along with the Catalyst launch, with just a few taps, the iPadOS app is now becoming a true native macOS app, a choice that just wasn’t possible with UIKit.

    Introduction to SwiftUI

    The SwiftUI framework is quite different from Cocoa. It operates on a programming paradigm that is completely unlike Cocoa. In SwiftUI, there is no storyboard, no nibs, and no outlets. There is no UIViewController, not even a UIView. Text is a struct, and View is just a protocol. A SwiftUI View is extremely lightweight.

    Declarative

    The declarative syntax is a paradigm of programming that allows you to write more formal and procedural code. The declarative syntax is a way of describing the code you want to write, without worrying about how it’s going to be implemented. Due to SwiftUI’s declarative nature of programming, it changes the paradigm of UI development by revealingly reducing lines of code.

    With iOS 13, developers were using UIKit with an imperative technique of UI development. It means that a developer needs to handle the events, UI transition, or maintain states by writing additional lines of code every single time an event should be reflected in the UI. With this technique, apps become more complicated and less readable.

    Imperative syntax:

    let labelText = UILabel(frame: CGRect(x:0, y:0, width:120, height:120))

    labelText.text = Understanding SwiftUI

    labelText.textColor = UIColor.red

    labelText.backgroundColor = UIColor.green

    labelText.font = UIFont(name: Consolas, size: 26)

    self.view.addSubview(labelText)

    Declarative Syntax (SwiftUI code):

    Text(Understanding SwiftUI)

    .foregroundColor(.blue)

    .background(Color.red)

    .font(.largeTitle)

    In the preceding code, we see two syntax structures of codes for a similar output. One is imperative nature, and the other is a declarative SwiftUI approach with not so much code but rather more comprehensible what is the issue with the imperative methodology is the developer need to assemble the code, over and over, to check the yield of the coding But in SwiftUI, revelatory user can see the coding yield promptly on the preview.

    Output:

    Figure 1.3: Output of declarative syntax

    With declarative methodology, Apple permits the developer to declare all states for the view at once, no longer needing to write the code for managing the states.

    SwiftUI completed this task for the developer to declare rules at the very beginning. The only task left for the developers is to shape the showcase model and refresh.SwiftUI will refresh the UI.

    When we used storyboards to make a UI, we got a huge XML document with complicated code that was hard to read. Lately, this XML document has been converted to machine code, and now no more complicated XML in SwiftUI.

    Automatic

    SwiftUI has no extensive needs for Interface Builder; Canvas, a responsive interface editor, replaced it. When writing code, the visual part in Canvas is automatically generated. When we use SwiftUI previews during development, you can quickly create more flexible and maintainable apps. It allows you to manage themes easily. Developers can easily add dark mode to their apps and set it as the default theme, and users can easily equip dark mode.

    It offers a Live Preview. This is a very opportune and reformer way to see the results of code execution in real-time without having to build.SwiftUI preview and also shows our designs in multiple screen sizes at the same time. This speeds up development.

    The SwiftUI architecture

    The Swift language is an open source, but SwiftUI is not open source and overseen by Apple. When you’ve taken in the nuts and bolts of SwiftUI, you’ve realized what you have to know to utilize SwiftUI anyplace. You can utilize the equivalent SwiftUI aptitudes for making an iOS application as you would for making an application on watchOS, tvOS, or macOS. So, the SwiftUI architecture tells you where SwiftUI exists in the development process.

    Figure 1.4: The SwiftUI architecture

    When SwiftUI sits on top of the application code and creates the application that displays UI elements, it does not create native elements from the code.

    Therefore, when a developer generates a text element, it does not produce a UILabel, an NSLabel, or a WKInterfaceLabel. It’s still a text element. However, they are shown independently in their hierarchies. All SwiftUI is stored in a container called hosting view.

    SwiftUI’s standard library is written in Swift. However, its core foundation is written in C++.

    Opaque types

    Starting in Swift 5.1 and iOS 13, a function return type can be specified as some supertype without stating subtype. The syntax is the keyword followed by the supertype.

    As an example of SwiftUI we can see this here:

    struct ContentView: View {

    var body: some View {

    Text(Hello, world!)

    .padding()

    }

    }

    struct ContentView_Previews: PreviewProvider {

    static var previews: some View {

    ContentView()

    }

    }

    In the preceding code, we can see some keywords, a View protocol requires a body computed property of type some View. We can hide the concrete return type of a computed property or function using some keyword, known as an opaque type.

    An opaque type describes a value in terms of the protocols it supports. Opaque return types as a function or method with an opaque return type hide its return value’s type information. Instead of providing a concrete type as the function’s return type.

    Let’s take an example.

    The following code snippets return the Text view (this is valid because Text conforms to the View protocol):

    var body: some View {

    Text(opaque type)

    }

    Other the Text view, you can also return a VStack view (which is also valid as VStack conforms to the View protocol):

    var body: some View {

    VStack {

    Text(opaque type)

    Image(systemName: manatsign.circle)

    }

    }

    Let’s create another example. In this example, we create a button, and on button click, we change the button label with the help of is Text and create an extension of ContentView to declare the functionality of the shapeOrText function:

    struct ContentView: View {

    @State private var isText = true

    var body: some View {

    Button{

    isText.toggle()

    }label:{

    shapeOrText()

    }

    }

    }

    Extension of ContentView:

    extension ContentView{

    func shapeOrText() -> some View{

    if isText {

    RoundedRectangle(cornerRadius: 10)

    .fill(Color.orange)

    .frame(width: 100, height: 100)

    }else

    {

    Text(SwiftUI)

    .font(.largeTitle)

    }

    }

    }

    The preceding code snippet will give the following error:

    Figure 1.5: Showing opaque return type error

    Function declared an opaque return type, but the return statements in its body do not have underlying matching types

    This is because, at compile time, the opaque return type cannot be determined. Is the body going to return a Text or Image view? This means no concrete type defined at return.

    So opaque return types are a specific type of protocol that works without exposing the concrete type to the API caller for better encapsulation. The preceding error may appear silly, but it makes sense given the preceding opaque type limitations. To remove this error, we can use some techniques:

    Group

    AnyView

    ViewBuilder

    Group

    If we wrap the if condition in Group, then our error gets removed and our code runs perfectly. No matter whether we send back a shape or a text view, they both go back in a group:

    extension ContentView{

    func shapeOrText() -> some View{

    Group{

    if isText {

    RoundedRectangle(cornerRadius: 10)

    .fill(Color.orange)

    .frame(width: 100, height: 100)

    }else

    {

    Text(SwiftUI)

    .font(.largeTitle)

    }

    }

    }

    }

    In the preceding code, we are not returning anything, and our functionality is working perfectly.

    AnyView

    AnyView is a type-erased view. It allows us to hide the real type of view. It allows multiple view types to be returned from a single function. It effectively makes Swift forget what type is contained within AnyView, making them appear to be the same. However, because this has a substantial cost, don’t use it frequently.

    Let’s use a type-erased wrapper AnyView that also return:

    extension ContentView{

    func shapeOrText() -> some View{if isText {

    return AnyView(RoundedRectangle(cornerRadius: 10)

    .fill(Color.orange)

    .frame(width: 100, height: 100))

    }else

    {

    return AnyView(Text(SwiftUI)

    .font(.largeTitle))

    }

    }

    }

    ViewBuilder

    The ViewBuilder function builder attribute plays a very central role in SwiftUI. We can use here a function builder:

    extension ContentView{

    @ViewBuilder

    func shapeOrText() -> some View{

    if isText {

    RoundedRectangle(cornerRadius: 10)

    .fill(Color.orange)

    .frame(width: 100, height: 100)

    }else

    {

    Text(SwiftUI)

    .font(.largeTitle)

    }

    }

    }

    We can use @ViewBuilder in different ways and have more importance in SwiftUI.

    All solutions are working perfectly fine

    SwiftUI for all Apple products

    What you learn in SwiftUI to other Apple platforms, for example, macOS is before the dispatch of SwiftUI, you’ll need to utilize platforms’ explicit UI structures to build up the UI. You use AppKit to compose UI for macOS applications and so forth.

    While utilizing SwiftUI, Apple offers designers a quandary UI system for building UIs on a wide range of Apple gadgets. The UI code composed for iOS can be effortlessly used on your iPadOS, macOS, and watchOS but might have to change a couple of modifiers, a couple of frame values, and stuff like that.

    But SwiftUI’s goal is clear, learn once and apply anywhere.

    As we show declarative code snippets, we create UILabel and then set its background and text color with font size. This code is specific for iOS as it uses the UILabel. UILabel is not available on macOS, which uses NSLabel, or the watchOS, which uses. With SwiftUI, there is a common element available on all iOS, iPadOS, macOS, and watchOS.

    SwiftUI doesn’t replace UIKit — like Swift and Objective-C, you can use both in the

    Conclusion

    In this chapter, we looked at SwiftUI, how it came to reality and the advantages of declarative development. We also touched upon how easy it is to write UI without worrying much about it in a much more declarative manner.

    The introduction of SwiftUI became a perfect buddy to Swift, opening up avenues not just for developers but also for designers and people just starting their journey into the world of Apple app development.

    Next, we are going to understand the basics of swift.

    Questions

    Which paradigms do SwiftUI and UIKit follow?

    What was Swift’s first big change?

    What is open-source software?

    For which platforms can SwiftUI be developed?

    CHAPTER 2

    Basic of Swift

    Introduction

    In this chapter, you will get a good overview of the Swift programming language. Although it is not possible to include a detailed discussion of the language in a single chapter, I cover most of the salient points of the language.

    If you are completely new to the Swift language of programming, it makes sense to read this chapter before proceeding with the rest of the book. The best way to learn Swift is to experiment within a Swift playground environment. Before starting this chapter, therefore, create a new playground and use it to try out the code.

    If you already have some basic knowledge of Swift, you can read this chapter to refresh your knowledge and see what has changed. Or, if you’re already writing iOS apps using Swift, use this chapter as a guide so that you can return to a subject quickly when clarification is needed.

    Structure

    The following topics will be covered in this chapter:

    Basic syntax of Swift

    Basic data types

    Arrays

    Dictionaries

    Optional types

    Flow control

    Looping

    Functions

    Class and structures

    Protocol

    Closure

    Objectives

    The objective of this chapter is to review the basic swift programming. With this chapter, we revise all important things about Swift. We understand the basic syntax of collections, functions, etc. We understand the class and structure, what is common, and what is different from them. We will also learn a bit about protocol and closure.

    Basic Swift syntax

    Swift is a type-safe language that ensures that the language endorses the values for which the code operates. The following sections discuss how to declare constants and variables.

    Constant

    In Swift, constants are declared using the let keyword:

    let myFullName = Mukesh Sharma   // String"

    let height = 5.5                                          // Double

    let numOfRow = 5                                  // Int

    You notice that we did not specify the data type — the data types are inferred automatically.

    If we want to declare the type of constant, we can do so using the colon operator (:) followed by the data type, as follows:

    let myFullName : String = Mukesh Sharma   // String"

    Apple suggests using constants rather than variables wherever possible for code efficiency and execution performance.

    Variables

    Variables are declared using the var keyword

    var userCount = 10

    var myAge = 34

    Variables may be initialized with a value at the time of creation. If the variable is declared without an initial value, it must be declared as being optional (will discuss optional later in this chapter).

    After a variable is created, you can change its value. In Swift, values are never implicitly converted to another type.

    Comments

    In Swift, like most programming languages, you insert comments into your code using two forward slashes (//):

    // your code

    The slashes signify to the compiler that the whole line is a comment and should be ignored.

    If we have several lines of comments, it’s better to use the /* and */ combination to denote a block of statements as comments:

    /*

    if(statement){

    }else {

    }

    */

    Basic data types

    Like other programming languages, Swift provides the following basic data types:

    Integers

    Floating-point numbers

    Booleans

    String

    Characters

    Tuples

    Integers

    Integers are whole numbers with no fractional parts. In Swift, integers are represented using the Int type, declaring Int implicitly as:

    let numberOfPages: Int = 10

    10

    let numberOfChapters = 3

    3

    The compiler always assumes that implicit declarations with integer values are of type Int, so both numberOfPages and numberOfChapters are integers. The Int type represents both positive and negative values. If you only need to store positive values, you can use the unsigned integer UInt type.

    Declaring Int explicitly as:

    let numberOfPeople: UInt = 20

    20

    let volumeAdjustment: Int32 = -1000

    -1000

    We can specify one of the various integer types available:

    Int8 and UInt8

    Int16 and UInt16

    Int32 and UInt32

    Int64 and UInt64

    Floating-point numbers

    Floating-point numbers are numbers with fractional parts. Swift has two basic floating-point number types:

    32 bits known as Float has a precision of at least six decimal digits

    64 bits known as Double has a precision of at least 15 decimal digits

    Bit sizes determine how much precision the numbers have. Double has more precision than Float, which means it can store more accurate approximations.

    Declaring floating-point number types:

    var d1 = 1.1

    //1.1

    let d2: Double = 1.1

    //1.1

    var d3 : Float = 3.14

    //3.14

    Swift always infers the Double type when assigning a floating-point number to a constant or variable unless explicitly specified otherwise. I believe in you; you will not try to assign a double value to float. If you then you need, cast double to a Float, like this explicitly:

    d3 = Float(d1)

    All the same numeric operators work on floating-point numbers except the remainder operator, only used on integers.

    Booleans

    Swift supports the Boolean logic type, Bool. Boolean values are referred to as logical. A Bool type can take either a true value or a false value. The following code snippet shows the Bool type in use:

    var seaIsRed = false

    var isSalesman : Bool = true

    Boolean values are particularly useful when we work with conditional statements such as the if statement:

    if seaIsRed {

    print(Transport did not denied the sale)

    } else {

    print(Transport denied the sale.)

    }

    One

    Enjoying the preview?
    Page 1 of 1