Contents

Swift Overview

Swift is a powerful and intuitive programming language developed by Apple Inc. for iOS, macOS, watchOS, and tvOS app development. It was first released in 2014 and has quickly gained popularity due to its simplicity, safety, and performance.

Key Features
  • Open Source: Swift is open-source, allowing developers to contribute and use it on a wide range of platforms.
  • Safety: Swift is designed with safety in mind, with features like optionals that help prevent null pointer errors.
  • Performance: Swift is optimized for performance, often outperforming Objective-C in various tasks.
  • Modern Syntax: Swift’s syntax is clean and concise, making it easier to read and write.

Swift Basic Syntax

Swift’s syntax is designed to be concise and expressive. Below are some basic syntax elements of Swift:

Hello, World! Example

Here’s a simple “Hello, World!” program in Swift:

				
					print("Hello, World!")
				
			

Identifiers

Identifiers are names used to identify variables, functions, or other user-defined items. They must begin with an alphabet (A-Z or a-z) or an underscore (_) and may contain letters, underscores, and digits. Swift is case-sensitive, so A and a are treated as distinct. Special characters like @, #, and % are not allowed in identifiers.

Examples:

				
					a, _temp, Temp, a_bc, a29b, temp12, temp_11

				
			

To use a reserved word as an identifier, enclose it in backticks (`).
Example:

				
					`exampleIdentifier`
				
			

Keywords

Keywords are reserved words with predefined meanings in Swift. They cannot be used as variable names or identifiers.

Examples of Keywords:

				
					class, func, let, public, struct, return, for, while, if, else, true, false

				
			

Every programming language has a set of reserved words used for internal processes or predefined actions. These reserved words, known as keywords, cannot be used as variable names, constant names, or other identifiers. To use a keyword as an identifier, enclose it in backticks (). For instance, while structis a keyword, “struct“ is a valid identifier. Note that backticks do not change the case sensitivity of identifiers (e.g.,aanda` are treated the same).

In Swift, keywords are categorized into the following groups:

1. Keywords in declaration
2. Keywords in statements
3. Keywords in expressions and types
4. Keywords in specific contexts
5. Keywords starting with the number sign (#)
6. Keywords used in patterns (_)

1. Keywords Used in Declarations: Keywords used in declarations include:

				
					associatedtype, class, deinit, enum, extension, fileprivate, func, import,
init, inout, internal, let, open, operator, private, precedencegroup,
protocol, public, rethrows, static, struct, subscript, typealias, var

				
			

Example:

				
					import Swift

// Creating a structure using the `struct` keyword
struct Employee {
    var name = "John"
    var id = 1234
}

// Creating an instance of the structure
var instance = Employee()

// Accessing properties of the structure
print("Employee Name:", instance.name)
print("Employee ID:", instance.id)

				
			

Output:

				
					Employee Name: John
Employee ID: 1234

				
			

2. Keywords Used in Statements: Keywords used in statements include:

				
					break, case, catch, continue, default, defer, do, else, fallthrough, for,
guard, if, in, repeat, return, throw, switch, where, while

				
			

Example:

				
					import Swift

// Finding the age group
let age = 70

if age >= 60 {
    print("Senior Citizen")
} else if age >= 40 {
    print("Middle-aged")
} else {
    print("Young")
}

				
			

Output:

				
					Senior Citizen

				
			

3. Keywords Used in Expressions and Types: Keywords in expressions and types include:

				
					Any, as, catch, false, is, nil, rethrows, self, Self, super, throw, throws, 
true, try

				
			

Example:

				
					import Swift

// Creating a class
class Person {
    func name() {
        print("Hello! My name is Alice")
    }
}

// Creating a subclass
class Employee: Person {
    override func name() {
        // Accessing the parent class method using `super`
        super.name()
        print("I work in the IT department")
    }
}

// Creating an instance of the subclass
let employee = Employee()
employee.name()

				
			

Output:

				
					Hello! My name is Alice
I work in the IT department

				
			

4. Keywords Used in Specific Contexts: Keywords used in specific contexts include:

				
					associativity, convenience, didSet, dynamic, final, get, indirect, infix,
lazy, left, mutating, none, nonmutating, optional, override, postfix,
precedence, prefix, Protocol, required, right, set, some, Type, unowned,
weak, willSet

				
			

Example:

				
					import Swift

// Creating a structure
struct Data {
    var value: String

    // Using the `mutating` keyword
    mutating func updateValue() {
        self.value = "Updated Value"
    }
}

var data = Data(value: "Initial Value")
data.updateValue()
print(data.value)

				
			

Output:

				
					Updated Value

				
			

5. Keywords Starting with the Number Sign (#): Keywords starting with # include:

				
					#available, #colorLiteral, #column, #dsohandle, #elseif, #else, #endif, 
#error, #fileID, #fileLiteral, #filePath, #file, #function, #if, 
#imageLiteral, #keyPath, #line, #selector, #sourceLocation, #warning

				
			

Example:

				
					import Swift

// Using `#function` to display the function name
func displayFunctionName() {
    print("You are in the function: \(#function)")
}

displayFunctionName()

				
			

Output:

				
					You are in the function: displayFunctionName
				
			

6. Keywords Used in Patterns (_): The underscore (_) is used as a wildcard in patterns.

Example:

				
					import Swift

// Printing a message 10 times
for _ in 1...10 {
    print("Swift Programming")
}

				
			

Output:

				
					Swift Programming
Swift Programming
Swift Programming
Swift Programming
Swift Programming
Swift Programming
Swift Programming
Swift Programming
Swift Programming
Swift Programming

				
			

Semicolons (;)

Semicolons are optional in Swift but are required when writing multiple statements on the same line.

Examples:

				
					var a = 1; var b = 2
print(a); print(b)
				
			

Output:

				
					1
2

				
			

Whitespaces

Whitespace separates elements in code and improves readability. It is mandatory between keywords and identifiers but optional elsewhere.

Examples:

				
					var a = 1
var b=2 // Valid but less readable
var c = a + b // Preferred for readability
				
			

Literals

Literals represent fixed values in a program, such as integers, decimals, strings, or booleans. These values can be directly used without computation. By default, literals in Swift don’t have a type. Primitive type variables can be assigned literals. For instance:

  • 12 is an integer literal.
  • 3.123 is a floating-point literal.
  • “Swift” is a string literal.
  • true is a boolean literal.
Swift Protocols for Literals

Literals must conform to specific protocols depending on their type:

  • ExpressibleByIntegerLiteral: For integer literals.
  • ExpressibleByFloatLiteral: For floating-point literals.
  • ExpressibleByStringLiteral: For string literals.
  • ExpressibleByBooleanLiteral: For boolean literals.

Example:

				
					let number: Int32 = 25
				
			
Types of Literals in Swift

1. Integer Literals: Used to represent whole numbers. If no alternate base is specified, they default to base-10 (decimal). Negative integers are represented using a minus sign (-).

Examples:

				
					let positiveNumber = 25
let negativeNumber = -25
let numberWithUnderscore = 2_500 // Same as 2500

				
			

Alternate Representations:

  • Binary: Prefix with 0b
  • Octal: Prefix with 0o
  • Hexadecimal: Prefix with 0x

Example

				
					let decimalNumber = 10
let binaryNumber = 0b1010
let octalNumber = 0o12
let hexadecimalNumber = 0xA

print("Decimal Number:", decimalNumber)
print("Binary Number:", binaryNumber)
print("Octal Number:", octalNumber)
print("Hexadecimal Number:", hexadecimalNumber)

				
			

Comments make code more understandable. They are ignored by the compiler.

Single-line comment syntax:

				
					Decimal Number: 10
Binary Number: 10
Octal Number: 10
Hexadecimal Number: 10

				
			

2. Floating-Point Literals: Represent numbers with a decimal point. The default type is Double. You can explicitly specify the type as Float.

Examples:

				
					let number: Int32 = 25
				
			

Exponential Representation:

				
					let scientificNumber1 = 1.25e3 // 1250
let scientificNumber2 = 1.25e-3 // 0.00125

				
			

Hexadecimal Floating-Point:

  • Prefix: 0x
  • Exponent: p
				
					let hexFloat1 = 0xFp1 // 30.0
let hexFloat2 = 0xFp-1 // 7.5

				
			

Example:

				
					let decimalFloatingNumber = 0.123
let scientificNotation = 1.23e2
let hexFloat = 0xFp1

print("Decimal Floating-Point:", decimalFloatingNumber)
print("Scientific Notation:", scientificNotation)
print("Hexadecimal Floating-Point:", hexFloat)

				
			

Output:

				
					\Decimal Floating-Point: 0.123
Scientific Notation: 123.0
Hexadecimal Floating-Point: 30.0

				
			

3. String Literals: Represent a sequence of characters enclosed in double quotes. Strings can be multi-line, escape special characters, or use interpolation.

  • Single-Line String:
				
					let message = "Hello, World!"
				
			
  • Multi-Line String:
				
					vlet multilineString = """
This is a
multi-line string.
"""

				
			
  • Escape Sequences:
				
					let escapedString = "Hello,\nWorld!"

				
			
  • String Interpolation:
				
					let name = "Swift"
let greeting = "Welcome to \(name) programming!"

				
			

Example:

				
					let singleLine = "Learning Swift"
let multiLine = """
Multi-line
String Example
"""
let interpolated = "The value is \(42)"

print(singleLine)
print(multiLine)
print(interpolated)

				
			

Output:

				
					Learning Swift
Multi-line
String Example
The value is 42

				
			

4. Boolean Literals: Boolean literals can be true or false. The default type is Bool.

Examples:

				
					let value1 = true
let value2 = false

print("Value 1:", value1)
print("Value 2:", value2)

				
			

Output:

				
					Value 1: true
Value 2: false

				
			

Comments

Comments make code more understandable. They are ignored by the compiler.

Single-line comment syntax:

				
					// This is a single-line comment

				
			

Multi-line comment syntax:

				
					/* 
This is a 
multi-line comment 
*/

				
			

Print Statement

The print function displays text, variables, or expressions on the screen.

Examples:

				
					print("Hello Swift") // Prints: Hello Swift

var x = 10
print(x) // Prints: 10

print(5 + 3) // Prints: 8

				
			

Output:

				
					Hello Swift
10
8
				
			

Import Class

The import keyword brings definitions from another module into the current program.

Syntax:

				
					import module

				
			

Examples:

				
					import Swift
print("Welcome to Swift Programming")

				
			

Output:

				
					Welcome to Swift Programming

				
			

Variables and Constants

Constants and variables in Swift are used to store data with specific types, such as numbers, characters, or strings. A constant cannot be changed after it has been assigned a value, whereas a variable can be modified during the program execution.

Declaring Constants & Variables in Swift

Constants and variables must be declared within their scope before being used. The let keyword is used for constants, and the var keyword is used for variables. Swift does not require semicolons (;) to terminate statements.

				
					let temperature = 20 // Declaring a constant
var count = 0        // Declaring a variable

				
			

You can declare multiple constants or variables in a single line, separated by commas:

				
					let x = 10, y = 20, z = 30 // Multiple constants
var p = 1, q = 2, r = 3    // Multiple variables

				
			
Type Annotation

Type annotation explicitly specifies the type of a constant or variable at the time of declaration. For example:

				
					var name: String // Declares a string variable without initialization
var age: Int     // Declares an integer variable

				
			

If multiple constants or variables are of the same type, you can declare them in one line:

				
					var firstName, lastName, city: String

				
			
Naming Constants & Variables

Names can contain any character except mathematical symbols, private Unicode scalar values, arrows, or whitespace characters:

				
					let pi = 3.14159
print("Value of pi: \(pi)")

				
			
Printing Constants & Variables

print() Function

The print(_:separator:terminator:) function is used to display the value of constants or variables.

Example:

				
					let country = "India"
print(country)

				
			

Output:

				
					India

				
			

String Interpolation: String interpolation allows embedding constants or variables directly within a string, replacing placeholders with actual values.

Example:

				
					var city = "Delhi"
print("I live in \(city)")

				
			

Output:

				
					I live in Delhi