Swift Programming Flashcards
IOS Programming
History of Swift ?
The history of Swift began in 2010 when an Apple engineer named Chris Lattner started working on a new programming language.
His main aim was to craft a programming language that is easy to use and more expressive just like high-level languages and provides great performance like low-level languages.
He achieves his goal by creating Swift programming language. So in 2014, Apple unveiled Swift to the world for the very first time at WWDC (World Wide Developer Conference) to replace Objective-C for iOS and macOS development.
Characteristics of Swift ?
Characteristics of Swift
- Modern Syntax − Swift provides clean and expressive syntaxes so that the developer can develop concise and easy-to-read programs. It makes it a more approachable language for both beginner and experienced developers.
- Safety − It increases safety by removing common bugs and errors. It incorporates modern programming techniques which makes it more secure and reliable.
- Performance − It provides high performance just like low-level languages while maintaining the safety and expressiveness of the code.
- Interoperability − Swift is an interoperable language. It works seamlessly with other languages like Objective-C. Developers are allowed to use Swift and Objective-C code together in the same project.
- Open Source − Swift is an open-source programming language that enhances the collaboration, innovation and ongoing improvements of Swift.
- Optionals − Swift provides great support to the optionals so that developers can explicitly represent the absence of value. It handles null or undefined values very well without the risk of runtime crash.
- Type inference − Swift supports a strong type system but it also incorporates with type interface to reduce the requirement of explicit type annotation. This means the Swift compiler is capable of analyzing the variables and expressions and determining their type.
- Automatic Memory Management − Swift uses Automatic Reference Counting to manage memory. It handles memory allocation and deallocation automatically without any lag. Because allocating memory manually is the common source of errors for the developers.
- Closures − Swift provides great support to the closures. Closure is a block code that can be referenced, passed around and executed later. They enhance the modularity and flexibility of the program.
- Protocol-Oriented Programming − Swift encourages protocol-oriented programming. It emphasizes the use of protocols to create blueprints for functionality. It creates reusable, modular and composable codes.
How are variables stored in Swift?
In Swift, values are stored in two types of containers: var for variables and let for constants. As the names imply, a variable’s value can change or be reassigned later in the program, while a constant’s value cannot.
What are Literals?
A literal is the source code representation of a value of an integer, floating-point number, or string type. Or we can say that literals are used to represent the actual values that are used to assign a constant or variable.
For example, 34 is an integer literal, 23.45 is a floating point literal. They are directly used in the program. We cannot directly perform operations on the literals because they are fixed values, but we can perform operations on the variables or constants (initialized with literals).
Type of Swift Literals:
* Integer literals
* Floating-point literals
* String literals
* Boolean literals
What is comments in Swift?
Comments are the special text in the programs that are not compiled by the compiler. The main agenda of the comments is to explain to us what is happening in the specific line of code or in the whole program. Programmers generally add comments to explain the line of codes in the program.
In Swift, we can define comments in three different ways −
- Single line comments
- Multi-line comments
- Nested Multi-line comments
Swift Advance Operators - Operator Overloading ?
Operator Overloading in Swift:
Operator overloading is a powerful technique in Swift programming. Operator overloading allows us to change the working of the existing operators like +, -, /, *, %, etc. with the customized code.
It makes code more expressive and readable. To overload an operator, we have to define the behaviour of that operator using the “static func” keyword.
Syntax:
Following is the syntax for operator overloading −
static func operatorName()
{
// body
}
Example 1
Swift program to overload + operator to calculate the sum of two complex numbers.
import Foundation
struct ComplexNumber {
var real: Double
var imag: Double
// Overloading + operator to add two complex numbers
static func+(left: ComplexNumber, right: ComplexNumber) -> ComplexNumber {
return ComplexNumber(real: left.real + right.real, imag: left.imag + right.imag)
}
}
let complexNumber1 = ComplexNumber(real: 2.1, imag: 2.0)
let complexNumber2 = ComplexNumber(real: 6.1, imag: 9.0)
// Calling + operator to add two complex //numbers
let sumOfComplexNumbers = complexNumber1 + complexNumber2
print(sumOfComplexNumbers)
Output:
ComplexNumber(real: 8.2, imag: 11.0)
Limitation of Operator Overloading in Swift :
The following are the limitations of operator overloading −
- In Swift, you can overload limited operators like arithmetic and customized operators.
- While overloading operators, you are not allowed to change the precedence or associativity of the operators.
- Swift does not support short-circuiting behaviour for overloading logical operators.
- Do not overuse operator overloading because it makes your code difficult to read and understand.
Difference Between Operator Function and Normal Functions ?
Operator Functions :
* They are define using “static func” keyword and a custom operator symbol.
* They are used to customize the behaviours of operators.
* They are called implicitly when using operator with custom types.
* They can be defined in index, prefix or postfix form.
Normal Functions:
* They are defined using “func” keyword and the function name.
* They are used to complete general purpose tasks.
* They are called explicitly with the help of function name.
* They can only defined in infix form.
Swift - Range Operators
Swift - Range Operators
Swift supports a special type of operator known as a range operator. The range operator is used to create a range of values. They are generally used with a for-in loop. There are three types of range operators are available in Swift −
- Closed Range :
Operator : (a…b)
Example : 1…4 return 1, 2, 3, 4 - Half-Open Range :
Operator : (a..<b)
Example : 1..<3 return 1, and 2 - One-Sided Range :
Operator : (a…) and (…a)
Example : (1..) return 1, 2, 3, … end of the element (…2) return beginning to 2
Swift - Data Types
While developing programs in any programming language, the utilization of variables is necessary for storing data. Variables are nothing but reserved memory locations to store data. This means that when we create a variable, we reserve some amount of space in memory.
Built-in Data Types in Swift:
- Int or Uint
- Float
- Double
- Bool
- String
- Character
- Optional
Bound Values:
- Int8
- UInt8
- Int32
- UInt32
- Int64
- UInt64
- Float
- Double
User-Defined Data Types in Swift
- Structures (Struct) : They are value types; means they can have copied when passed around in the program. They are good for representing simple data structure.
- Class : They are reference types; means they are passed as a reference. They are good for complex data models and objects.
- Enumarations (Enum) : They are used to define a group of related values. They are good at representing finite set.
- Protocols : They define a blueprint for methods and properties that is good for a particular task or piece of functionality.
Swift - Optionals
Swift - Optionals
Swift introduced a new feature named Optional type. The optional type handles the value that may be absent or undefined. It allows variables to represent a value or nil. The Optional are similar to using nil with pointers in Objective-C, but they work for any type, not just classes. To specify the optional type we have to use question marks(?) after the name of the type.
Syntax:
Following is the syntax for the optional variable −
var perhapsInt: Int?
Example:
Swift program to demonstrate how to create optional variable.
// Declaring an optional Integer
var number: Int?
// Assigning a value to the optional
number = 34
// Using optional binding to safely unwrap its value
if let x = number {
print(“Value is (x)!”)
} else {
print(“Value is unknown”)
}
Output:
Value is 34!
What is meaning of below text into Swift?
* Optionals with nil
* Forced Unwrapping
* Implicitly UnWrapping Optional
* Optional Binding
* Nil-Coalescing Operator(??)
1. Optionals with nil:
If we want to specify an optional variable to a valueless state or no value, then we can assign nil to that variable. Or if we do not assign any value to an optional variable, then Swift will automatically set the value of that variable to nil. In Swift, we are only allowed to assign nil to an optional variable, if we try to assign nil to a non-optional variable or constant, then we will get an error.
Syntax:
Following is the syntax for assigning optional to nil −
var perhapsStr: Int? = nil
2. Forced Unwrapping
If you defined a variable as optional, then to get the value from this variable, you will have to unwrap it. So to unwarp the value we have to put an exclamation mark(!) at the end of the variable. It tells the compiler that you are sure that the optional contains some value.
Syntax:
Following is the syntax for forced unwrapping −
let variableName = optionalValue!
3. Implicitly Unwrapping Optional
You can declare optional variables using an exclamation mark instead of a question mark. Such optional variables will unwrap automatically and you do not need to use any further exclamation mark at the end of the variable to get the assigned value.
Example:
import Cocoa
var myString:String!
myString = “Hello, Swift 4!”
if myString != nil {
print(myString)
}else{
print(“myString has nil value”)
}
Output: Hello, Swift 4!
4. Optional Binding
Use optional binding to find out whether an optional contains a value, and if so, to make that value available as a temporary constant or variable. Or we can say that optional binding allows us to unwarp and work with the value present in the optional. It prevents us from unwrapping nil values and runtime crashes.
We can perform optional binding using if let, guard, and while statements. We are allowed to use multiple optional binding and boolean conditions in a single if statement, separated by a comma. If any of the optional binding or boolean conditions among the given multiple optional bindings and boolean conditions are nil, then the whole if statement is considered to be false.
Syntax:
Following is the syntax for the optional binding −
if let constantName = someOptional, let variableName = someOptional {
statements
}
5. Nil-Coalescing Operator(??)
In Swift, we can also handle missing values and provide a default value if the optional is nil using the nil-coalescing operator(??). It is the shorthand method of using optional binding along with default value.
Syntax
Following is the syntax for the nil-coalescing operator −
Let output = optionalValue ?? defaultValue
The nil-coalescing operator (??) operator checks if the value on the left hand-side operand is not nil. If it is not nil, then it unwraps the value. If the value is nil, then it will provide the value (or as a fallback value) present in the right hand-side operand.
Swift - Tuples
Swift - Tuples:
Tuples are used to store a group of values in a single value, for example (32, “Swift Programming”) is a tuple with two values that are 32 and “Swift Programming”. Tuples can store multiple values and each value is separated by a comma. It can store values of the same or different data types. They are helpful when we want to return multiple values together.
Tuples are commonly used by the functions to return multiple values at the same time. Tuples are not used for complex data structures; they are useful for simple groups of related data.
Syntax:
Following is the syntax of the Tuple −
var myValue = (value1, value2, value3, value4, …, valueN)
We can access the elements of the tuple with the help of dot notation followed by the element’s index −
var result = tupleName.indexValue
Example:
Swift program to create and access the elements of the tuple.
import Foundation
// Creating a tuple
var myTuple = (“Romin”, 321, “Delhi”)
// Accessing the elements of Tuple
var name = myTuple.0
var id = myTuple.1
var city = myTuple.2
// Displaying the result
print(“Employee name =”, name)
print(“Employee id =”, id)
print(“Employee city =”, city)
Output:
Employee name = Romin
Employee id = 321
Employee city = Delhi
Swift - Assertions and Precondition
Swift - Assertions and Precondition
Swift provides two special mechanisms: assertions and preconditions which allow the developers to enforce some special conditions in their programs for debugging and ensuring the correctness of the program. Both methods create robust and reliable Swift applications by catching and addressing unexpected situations occurring during the different stages of application development.
Swift Assertions
Assertion is a powerful debugging tool to check and fix errors or bugs in the development process of an application. Or we can say that its main purpose is to catch and identify errors or bugs at the runtime. It is represented in a boolean condition, if the condition is evaluated to true, then the program will continue its execution. Whereas if the condition is evaluated as false, then the execution of the program will end. Assertion is non-recoverable, which means if the assertion fails we cannot recover it or catch it. We can achieve assertion using the assert() function.
The assert(::file:line) function performs a runtime check during the development. Or we can say that it implements C-style assert.
Syntax
Following is the syntax for the assert() function −
func assert(_condition: @autoclosure()->Bool,
_message: @autoclosure() -> String = String(),
file: StaticString = #file,
line: UInt = #line)
Parameters
This function takes the following parameters −
* condition − It represents the test condition.
* message − It represents the message that will be displayed when the condition is set to false. By default, its value is empty.
* file − It represents the file name where the assertion is present and will display along with the message if the assertion is failed. It is an optional parameter.
* line − It represents the line number where the assertion is present and will display along with the message if the assertion is failed. It is an optional parameter.
Swift Precondition
Precondition is used to catch and handle unexpected states and assumptions at the time of execution of the code. Or we can say that precondition helps the developer to find issues in the production state of the application.
It is also represented in a boolean condition, if the condition is evaluated to true, then the program will continue its execution. Whereas if the condition is evaluated as false, then the execution of the program will end. It is also non-recoverable. We can achieve precondition using the precondition() function.
The precondition(::file:line) function is used to enforce a condition during the execution of the program.
Syntax
Following is the syntax for the assert() function −
func precondition(_condition: @autoclosure()->Bool,
_message: @autoclosure() -> String = String(),
file: StaticString = #file,
line: UInt = #line)
Swift Collections - Arrays
Swift Collections - Arrays
Arrays are used to store ordered lists of values of the same type. Swift puts strict checking which does not allow you to enter a wrong type in an array, even by mistake.
An array can store duplicate values in different positions. Each element in the array has an index value starting from 0 so that we can access and modify them using that index.
Creating Arrays in Swift:
We can create an array by specifying the type of the array explicitly.
Syntax:
Following is the syntax for creating an array −
var someArray : [Type] = []
We can also create an array without specifying its type. In this case, the compiler will automatically get the type of the array based on the assigned value.
var someArray = [value1, value2, value3]
If you need to create an array with a single value (by repeating it), you can do so using the Array() initializer.
var someInts = Array(repeating: “Swift”, count: 4)
Modifying and Accessing Arrays in Swift:
In an array, every element has its own index value starting from 0. So to retrieve a value from an array, pass the index of the value we want to retrieve within square brackets immediately after the name of the array in the subscript syntax.
Syntax
Following is the syntax for accessing and modifying array −
arrayName[indexValue]
Adding a New Element in an Array in Swift:
We are allowed to add new elements to the existing array using the following methods.
- Using append() Method
- Using the addition assignment operator (+=)
Iterating Over an Array in Swift:
Iterating over an array is the fundamental and most commonly used operation in programming. It allows the developer to access and process individual elements of the specified array. In Swift, we can iterate over an array using the following methods −
- Using for-in loop:
Example
import Foundation
// Defining and initializing an array
var someArr:[Int] = [3, 56, 12, 4, 23, 5, 6, 7, 8]
print(“Array Elements:”)
// Iterating over the array using a for-in loop
for x in someArr{
print(x)
}
- Using the enumerated() function with for-in loop
Example
import Foundation
// Defining and initializing an array
var someArr:[Int] = [3, 56, 23, 34, 5, 78, 9]
print(“Array Elements with their index value:”)
// Iterating over the array using for-in loop along with enumerated() function
for (index, element) in someArr.enumerated() {
print(“Value at index = (index) is (element)”)
}
- Using while loop
Example
import Foundation
// Defining and initializing an array
var someArr:[Int] = [3, 56, 23, 34, 5, 78, 9]
print(“Array Elements:”)
var indexVal = 0
// Iterating over the array using while loop
while indexVal < someArr.count {
print(someArr[indexVal])
indexVal += 1
}
- Using forEach() Function
Example
import Foundation
// Defining and initializing an array
var someArr:[String] = [“Mona”, “Pihu”, “Mayank”, “Sumit”]
print(“Array Elements:”)
// Iterating over the array using forEach() function
someArr.forEach { names in
print(names)
}
Swift Collections - Sets
Swift Collections - Sets
Swift sets are used to store distinct values of the same types but they don’t have definite ordering as arrays have. It runs a strict type checking which means you are not allowed to enter a wrong type in an array, even by mistake.
Creating Sets in Swift :
To create an empty set of a certain type we can use the Set() initializer. It explicitly accepts the data type. A set can store the value of any data type like float, integer, string, character and double.
var someSet = Set<DataType>()</DataType>
We can also create an empty set using the array literal. It is the shorthand representation of a set.
var someSet : Set<DataType> = [value]
Or
var someSet : Set = [value]</DataType>
Initializing Sets in Swift :
We can initialize the set using the following methods −
1. Using insert() method
2. Using array literal
Iterating over a Set in Swift:
Iterating over a set allows the developer to access and process individual elements of the given set. In Swift, we can iterate over a set using the following methods −
- Using for-in loop
- Using the enumerated() Function with for-in loop
- Using forEach() Function
Set Operations in Swift:
Set operations are used for combining, comparing and manipulating sets. A set supports five types of operations −
- Union
- Intersection
- Subtraction
- Difference
- Subset