Swift Tutorial (Programing Language)

By: Luis A. Sierra


Introduction

Swift is the powerful, flexiblemultiplatform programming language.

Fast. Expressive. Safe.

Swift is used to develop IOS apps, Windows appsserver side appsEmbedded software for ARM and RISC-V microcontrollers and Machine Learning & AI

What is Swift

Swift is a high-level general-purpose, multi-paradigm, compiled programming language created by Chris Lattner in 2010 for Apple Inc. and maintained by the open-source community. Swift compiles to machine code and uses an LLVM-based compiler. Swift was first released in June 2014 and the Swift toolchain has shipped in Xcode since Xcode version 6, released in September 2014.

Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns. Originally developed by Apple for building iOS, macOS, watchOS, and tvOS applications, Swift’s project goal is to create the best available language for uses ranging from systems programming to mobile and desktop apps, scaling up to highly distributed cloud services. Swift’s rich ecosystem of libraries allows services to be developed and deployed on Linux or macOS. Most importantly, Swift is designed to make writing and maintaining correct programs simple for developers.

Swift is a general-purpose programming language with unique characteristics that make it specifically suitable for Server applications.

Swift on Server refers to the ability to use the Swift programming language for server-side development. To deploy Swift applications on the server, developers can make use of web frameworks such as Vapor and Hummingbird which provide a variety of tools and libraries to streamline the development process. These frameworks handle important aspects like routing, database integration, and request handling, allowing developers to focus on building the business logic of their applications.

Various companies and organizations have adopted Vapor and Hummingbird to power their production services.

Swift has support for bidirectional interoperability with C++. A great variety of C++ APIs can be called directly from Swift, and select Swift APIs can be used from C++.

Swift for Server

Swift on Server provides developers with a modern, safe, and efficient option for writing server-side code. Swift combines the simplicity and readability of a high-level language with the performance and safety features of a compiled language, allowing developers to leverage their existing Swift skills to build complete end-to-end solutions using a single programming language.

In addition to the characteristics of Swift that make it an excellent general-purpose programming language, it also has unique characteristics that make it specifically suitable for server applications due to its:
  • Performance.
  • Quick start-up time.
  • Expressiveness and safety.
  • Supported ecosystem.

Performance

Swift offers fast performance and a low memory footprint. Instead of tracing garbage collection, it uses Automatic Reference Counting (ARC) and ownership features, which allows precise control over resources. Swift’s use of ARC and its lack of just-in-time (JIT) compilation provides an edge in the cloud services space.

While tracing garbage collection technologies have improved, they still compete with the application for resources, triggering non-deterministic performance. Debugging non-deterministic performance and language-induced non-deterministic performance can confuse and mask application-level performance issues that can otherwise be addressed.

One of the main goals of a modern cloud platform is to maximize resource utilization by efficiently packing services into a single machine. Cloud services built with Swift have a small memory footprint (measured in MB), especially compared to other popular server languages with automatic memory management. Services built with Swift are also CPU-efficient, given the language’s focus on performance.

While Java, PHP, Python, and JavaScript have their strengths and use cases, Swift offers several advantages over other programming languages. For example, Swift’s performance is comparable to languages like C and C++, making it well-suited for building high-performance server applications. Thanks to the progressive and efficient design of the language, Swift server-side applications can handle large-scale workloads with high performance and low resource consumption.

These characteristics make Swift ideal for use in modern cloud platforms when maximizing resource utilization is needed.

Platforms

The platforms Swift supports are Apple's operating systems (Darwin, iOS, iPadOS, macOS, tvOS, watchOS), Linux, Windows, and Android

A key aspect of Swift's design is its ability to interoperate with the huge body of existing Objective-C code developed for Apple products over the previous decades, such as Cocoa and the Cocoa Touch frameworks. On Apple platforms,it links with the Objective-C runtime library, which allows C, Objective-C, C++ and Swift code to run within one program.

IDEs


XCode is Apple’s IDE that developers can use to build codes for iPhones, iPad and other device-based applications. You can use the IDE to develop code using Swift programming language. It also extends support for multiple programming languages, which makes it the most superior programming language.


This intelligent integrated development environment was created to support Objective-C and Swift programming languages. It comes with modern libraries and support for modernized coding that enables swift solutions.



This is one of the best and most popular Swift IDEs you can use to build iOS applications. CodeRunner is devised only for iOS, so it doesn’t extend cross-platform support.

This is an intelligent and cross-platform IDE developed by JetBrains to help program applications using Swift language. It does offer a debugger and a powerful editor that helps build the code. You can use several analysis tools for the best outcomes and quick coding decisions.

Swift Get Started

Installing Xcode and Simulators

iOS, iPadOS, and (on a Mac with Apple silicon) visionOS simulators are available in macOS as part of Xcode, which is free in the Mac App Store.

To get started using Simulators:

Install Xcode from the Mac App Store.

Once installed, launch Xcode so that it can complete its first launch.

A dialog will be presented that indicates which Simulator runtimes are built-in, and which Simulator runtimes you may download. For now, choose Continue to finish setting up Xcode.

Hello World application

Hello, World! It is the first basic program in any programming language. Let's write the first program in the Swift programming language.

1 - Open Xcode


2 - Now go to File -> Playground in Xcode

3 - Now select IOS -> Blank and Click on Next Button  in Xcode


4 - Now enter the name "HelloWorld.playground" and choose a  folder to save he project and Click on Create Button  in Xcode:


5 - Now enter the code below:

import UIKit


print("Hello World!")


6 - Now go to Editor -> Run Playground in Xcode


7 - After that you will see de result


⚠️ ⚠️ Xcode Important Notes ⚠️⚠️

Use: "import Cocoa" For MacOS App

Use: "import UIKit" For iOS App

You can use import to import any Objective-C Framework or C Library Directly to your Swift Application


Cocoa is implemented in Objective-C with is a superset of C, so it is easy to mix C/C++ in your Swift Application

For non-macOS users ðŸ˜Ž 


Code: print("Hello World!")

You can test your code here: ðŸ‘‰ https://www.onlineide.pro/playground/swift

Swift Comments

Comments can be used to explain swift code, and to make it more readable. It can also be used to prevent execution when testing alternative code.

Single-line comments starts with two forward slashes (//).

// This is a comment
print("Welcome to http://interesting-homemade-projects")

Multi-line comments start with  /* and ends with */.

/* The code below will print the url of my web site
to the screen */

print("Welcome to http://interesting-homemade-projects")

Swift Variables

Variables are the "place" where we can store the data that the program needs.

To create a variable, use var or let and assign a value to it with the equal sign (=):

var Thousand = 1000;
print(Thousand)
var Pi = 3.14;
print(Pi)
var AuthorName = "Luis A. Sierra";
print(AuthorName)


Note:

The difference between var and let is that variables declared with the var keyword can be changed/modified, while let variables cannot.

Case Sensitivity

Case sensitivity defines whether uppercase and lowercase letters are treated as distinct or equivalent.

"Swift : is case sensitive"

Swift Data Type

In Swift, the type of a variable is decided by its value:

import UIKit


var id = 10                           // Int

var percentage = 18.55                // Double

var gender = "M"                      // Char

var isVerified = true                 // Boolean

var name = "Luis A. Sierra"           // String


print("Id: \(id)")

print("Name: \(name)")

print("Percentage: \(percentage)")

print("Gender: \(gender)")

print("Verified: \(isVerified)")



However,it is possible to specify the type if you want:


import UIKit


var id : Int = 10                          // Int

var percentage  : Double  = 18.55          // Double

var gender : Character = "M"               // Char

var isVerified  : Bool = true              // Boolean

var name : String =  "Luis A. Sierra"      // String


print("Id: \(id)")

print("Name: \(name)")

print("Percentage: \(percentage)")

print("Gender: \(gender)")

print("Verified: \(isVerified)")



Sometimes you have to specify the type, and often you don't. Anyhow, it is good to know what the different types represent.



Type Conversions

Is the process of converting one data type to another. The type conversion is only performed to those data types where conversion is possible.


Example:

let num: Int = 10
let dec: Double = 5.25
let boolean: Bool = true

print(String(num)) // Convertir a String
print(Double(num)) // Convertir a Double
print(Int(dec)) // Convertir a Int
print(String(boolean)) // Convertir a String



MORE EXAMPLES:

* Convert to String


* Convert to Integer


* Convert to Double


* Convert to Boolean


* Convert to Date


* Convert to Time


* Convert to DateTime


* Format DateTime


* DayName of DateTime


* Convert to ASCII


* String Replace


* String Length


* String Copy

Swift Array

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.


Array Length / Size


Operators

Is a character that represents a specific mathematical or logical action or process.

In Swift different types of operators are available; those are:

  • Arithmetic Operators
  • Comparison Operators
  • Logical Operators
  • Bitwise Operators
  • Assignment Operators
  • Range Operators
  • Misc Operators

Arithmetic Operators

Arithmetic operators are used to perform common mathematical operations.


Comparison Operators

Comparison operators are used to compare two values (or variables). This is important in programming, because it helps us to find answers and make decisions.


Logical Operators

Logical operators are used to determine the logic between variables or values:


Bitwise Operators

bitwise operators are used to perform operations directly on the binary representations of numbers.



Assignment Operators

Assignment operators are used to assign values to variables.


Range Operators

The range operator is used as a shorthand way to set up arrays. When used with arrays, the range operator simplifies the process of creating arrays with contiguous sequences of numbers and letters.


Misc Operators

misc operator is miscellaneous operator, which is conditional operator which has 3 operands,The first operand is always evaluated first.


if/else Statement

The if-else statement is used to execute both the true part and the false part of a given condition. If the condition is true, the if block code is executed and if the condition is false, the else block code is executed


Case Statement

The CASE expression goes through conditions and returns a value when the first condition is met (like an if-then-else statement)


While Statement

A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition.


For Statement

The for statement, also called the for loop, lets you repeat a statement or compound statement a specified number of times.


For with _ :


For with ranges:


Function

A function, subprogram, procedure, method, routine or subroutine is a callable unit that has a well-defined behavior and can be invoked by other software units to exhibit that behavior.

Note: functions return and not return a value.


Class

A class is an extensible program-code-template for creating objects, providing initial values for state (member variables) and implementations of behavior (member functions or methods).


Constructor

In class-based, object-oriented programming, a constructor (abbreviation: ctor) is a special type of function called to create an object. It prepares the new object for use, often accepting arguments that the constructor uses to set required member variables.


Properties

Properties are special attributes or characteristics associated with an object. They encapsulate data and provide access control through getter and setter methods, allowing you to interact with the object's state without directly accessing its variables.


Inheritance

Inheritance is one of the core features of object-oriented programming. It's a programming procedure that allows you to reuse code by referencing the behaviors and data of an object. In other words, a class that inherits from another class shares all the attributes and methods of the referenced class.

Swift supports the following type of inheritance 
  • Single
  • Multilevel
  • Hierarchical
Single Inheritance


Multilevel Inheritance

The inheritance in which a class can be derived from another derived class is known as Multilevel Inheritance.


Hierarchical Inheritance

Hierarchical inheritance refers to an inheritance where multiple classes will derived from a single base class. These classes can access and override the properties and methods of the base class and can have their own properties and methods.


Exception handling

Exception is typically used to denote a data structure storing information about an exceptional condition. One mechanism to transfer control, or raise an exception, is known as a throw; the exception is said to be thrown. Execution is transferred to a catch.




Post a Comment

Previous Post Next Post