Swift Programming Flashcards

IOS Programming

1
Q

History of Swift ?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Characteristics of Swift ?

A

Characteristics of Swift

  1. 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.
  2. Safety − It increases safety by removing common bugs and errors. It incorporates modern programming techniques which makes it more secure and reliable.
  3. Performance − It provides high performance just like low-level languages while maintaining the safety and expressiveness of the code.
  4. 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.
  5. Open Source − Swift is an open-source programming language that enhances the collaboration, innovation and ongoing improvements of Swift.
  6. 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.
  7. 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.
  8. 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.
  9. 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.
  10. 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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How are variables stored in Swift?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are Literals?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is comments in Swift?

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Swift Advance Operators - Operator Overloading ?

A

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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Difference Between Operator Function and Normal Functions ?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Swift - Range Operators

A

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 −

  1. Closed Range :
    Operator : (a…b)
    Example : 1…4 return 1, 2, 3, 4
  2. Half-Open Range :
    Operator : (a..<b)
    Example : 1..<3 return 1, and 2
  3. One-Sided Range :
    Operator : (a…) and (…a)
    Example : (1..) return 1, 2, 3, … end of the element (…2) return beginning to 2
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Swift - Data Types

A

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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Swift - Optionals

A

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!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is meaning of below text into Swift?
* Optionals with nil
* Forced Unwrapping
* Implicitly UnWrapping Optional
* Optional Binding
* Nil-Coalescing Operator(??)

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Swift - Tuples

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Swift - Assertions and Precondition

A

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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Swift Collections - Arrays

A

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.

  1. Using append() Method
  2. 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 −

  1. 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)
}

  1. 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)”)
}

  1. 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
}

  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)
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Swift Collections - Sets

A

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 −

  1. Using for-in loop
  2. Using the enumerated() Function with for-in loop
  3. 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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Swift Collections - Dictionaries

A

Swift Collections - Dictionaries

Dictionaries are used to store unordered lists of values of the same type. Swift puts strict checking which does not allow you to enter a wrong type in a dictionary even by mistake.

Dictionaries use a unique identifier known as a key to store a value which later can be referenced and looked up through the same key. Unlike arrays, items in a dictionary do not have a specified order. You can use a dictionary when you need to look up values based on their identifiers. In a dictionary, a key can be either an integer or a string without restriction, but it should be unique within a dictionary. Whereas values can be duplicated.

If you assign a created dictionary to a variable, then it is always mutable which means you can change it by adding, removing, or changing its items. But if you assign a dictionary to a constant, then that dictionary is immutable, and its size and contents cannot be changed.

Creating Dictionary in Swift:
A dictionary contains a key-value pair. The type of key-value pair can be the same or different means it is not necessary that the type of the key and value should be the same. So we can create a dictionary of a certain type using the following syntax.

Syntax
Following is the syntax for creating a dictionary −
var someDict = KeyType: ValueType

We can also create a dictionary without specifying its type. In this case, the compiler will automatically get the type of the dictionary based on the assigned value. Following is the syntax for creating a dictionary −

var someArray = [key1: value, key2: value, key3: value3]

Filtering Elements of the Dictionary in Swift:
To filter the elements of the dictionary swift provides a pre-defined function named filter(). The filter() function takes a closure as a parameter and returns a new dictionary that contains only those key-value pairs that match the given condition in the closure.

Syntax
Following is the syntax of the filter() function −

func filter(closure)

Example
import Foundation

// Defining and initializing a dictionary
var myDict = [3: “Blue”, 4: “Pink”, 5:”Green”, 7:”Pink”]

// Filtering out only pink color using filter() function
let color = myDict.filter { $0.value == “Pink” }

print(color)

Output
It will produce the following output −
[4: “Pink”, 7: “Pink”]

Accessing Dictionaries in Swift:
To access the key-value pairs of the given dictionary we can use any of the following methods −

  1. Using Subscript Syntax
    var someVar = someDict[key]
  2. Using keys Property
    3.Using values Property

Modifying Dictionaries in Swift:
To modify the existing value of the associated key Swift provides a predefined method named updateValue(forKey:). If the given key-value pair is not present in the given dictionary, then this method adds that pair to the dictionary. This method returns a replaced value or nil if it adds a new key-value pair.

Syntax
Following is the syntax for the updateValue() function −

func updateValue(value, forKey: key)

Modifying elements in a Dictionary :
We can modify an existing element of a dictionary by assigning a new value at a given key using []. The bracket[] changes the value of the specified key in the given dictionary.

Syntax
Following is the syntax for updating the value −

Dictionary[key] = value

Remove Key-Value Pairs from a dictionary :
Remove Key-Value Pairs from a dictionary
To remove key-value pair from a dictionary Swift provides a pre-define function named removeValue(forKey:) method. This method removes the specified key and its related value if it exists and returns the removed value, or returns nil if no value exists.

Syntax
Following is the syntax of the removeValue() property −

Dictionary.removeValue(forKey: Key)

Removing all the elements at once:
Swift provides one more pre-defined method named removeAll(). This method removes all the keys and their associated values from the given dictionary.

17
Q

Swift - Functions

A

Swift - Functions

A function is a set of statements organized together to perform a specific task. A Swift function can be as simple as a simple C function to as complex as an Objective C language function. It allows us to pass local and global parameter values inside the function calls. Also, we can define a function inside another function to encapsulate its functionality inside another function.

Function plays an important role in structuring code, modularity and increasing code readability. They also provide various features such as parameter labels, default parameter values, variadic parameters, and multiple return types.

In Swift, a function is defined by the “func” keyword. When a function is newly defined, it may take one or several values as input ‘parameters’ to the function and it will process the functions in the main body and pass back the values to the functions as output ‘return types’.

Every function has a function name, which describes the task that the function performs. To use a function, you “call” that function with its name and pass input values (known as arguments) that match the types of the function’s parameters. Function parameters are also called as ‘tuples’.

A function’s arguments must always be provided in the same order as the function’s parameter list and the return values are followed by ->.

Syntax
Following is the syntax for creating a function −

func funcname(Parameters) -> returntype {
Statement1
Statement2

Statement N
return parameters
}

Type of Function Parameters in Swift
Parameters are the variables that are specified in the function declaration to get input when the function is called. Swift function supports the following types of parameters :-

  • Regular Parameters
  • Varadic Parameters
  • In-Out parameters

1. Regular Parameters :
Syntax
Following is the syntax for regular parameters −
func funcname(name1: Type, name2:Type = defualtValue) -> returntype {
Statement
return value
}

2. Varadic Parameters :
Swift provide a special type of parameter named a varadic parameter. The variadic parameter allows us to accept multiple input values of the same type in the function. This parameter is useful when we want to pass an arbitrary number of values of the same type inside the function without specifying the exact count of the values.

Syntax
Following is the syntax for variadic parameters −
func funcname(_name1: Type…, name2:Type…, name3: Type…) -> returntype
{
Statement
return value
}

3. In-Out parameters:
In-Out parameters in Swift provide the functionality to retain the parameter values even though their values are modified after the function call. At the beginning of the function parameter definition, ‘inout’ keyword is declared to retain the member values.

It derives the keyword ‘inout’ since its values are passed ‘in’ to the function and its values are accessed and modified by its function body and it is returned back ‘out’ of the function to modify the original argument. The in-out parameter does not contain a default value.

Variables are only passed as an argument for in-out parameters since their values alone are modified inside and outside the function. Hence no need to declare strings and literals as in-out parameters. ‘&’ before a variable name refers to that we are passing the argument to the in-out parameter.

Example
Swift program to demonstrate how to create a function with in-out parameters.
// Function to swap two values
func swap(_ x: inout Int, _ y: inout Int) {
let temp = x
x = y
y = temp
}

var p = 15
var q = 10

print(“Before swapping: p = (p), q = (q)”)

swap(&p, &q)

print(“After swapping: p = (p), q = (q)”)

Output :
It will produce the following output −
Before swapping: p = 15, q = 10
After swapping: p = 10, q = 15

18
Q

Swift - Recursion

A

Recursion is a technique in which a function calls itself directly or indirectly to solve a problem. Instead of solving the entire problem at once it divides the problem into smaller sub-problems and then solves them by calling itself repeatedly until it reaches to the base condition. A recursive function has two main components −

  • Base condition − The base condition is responsible for stopping the recursive call. Or it is a termination point where it prevents the function from calling itself infinitely. If we do not specify the base condition in the recursive function, then it will call itself infinitely and the program will never end.
  • Recursive call − Recursive call is where the function calls itself with modified parameters to solve the task. With iteration, the recursive call should move towards the base condition so that it terminates successfully without entering into infinite recursion.

Need for Recursion in Swift
Recursion is a compelling technique for solving larger programming problems very easily. We can use recursion in the following scenarios −

  • Divide and Conquer − Recursive algorithms use divide and conquer approaches, they divide the complex problems into small identical sub-problems and solve them in each recursive call.
  • Tree and Graph Traversal − Recursive functions are generally used to traverse trees and graphs in data structures.
  • Code Readability − Recursion results are much more readable and manageable as compared to iterative approaches.
  • Mathematical calculations − Using recursion we can solve various mathematical problems like factorial, Fibonacci numbers, etc.
  • Natural Representation − Recursion gives a natural and intuitive representation of the problems that exhibit the recursive properties.
19
Q

Swift - Higher-Order Functions

A

Swift - Higher-Order Functions

A higher-order function is a special type of function; it takes one or more functions as arguments or can return a function as its result. They can easily manipulate and transform the data of the given collections without creating any extra user-defined function. Below are the higher-order functions provided by the Swift language −

  • forEach()
  • map()
  • compactMap()
  • flatMap()
  • filter()
  • reduce()
  • sort()
  • sorted()

All the higher-order functions are based on closure.

1. The forEach() Function:
The ForEach() function is quite similar to the for-in loop. It will iterate through all the elements in a collection (eg array) and not return anything. Remember that you cannot use continue and break inside the forEach() function to exit the currently executing statement.
Example

Swift program to display all the elements of the array using the forEach() function.

import Foundation
let numbersInWord = [“One”, “Two”, “Three”, “Four”, “Five”, “Six”]
numbersInWord.forEach {
element in print(element)
}

Output:
It will produce the following output −
One
Two
Three
Four
Five
Six

2. The map() Function :
The map function works by performing an operation on all the elements of a collection and returning a new collection with the results of that operation. This function is designed to transform an object from one type to another type (as well as the same type).

Example
Swift program to convert int to a string using the map() function.

import Foundation
let numbers = [1, 2, 3, 4, 5, 6, 7]
let numbersInString = numbers.map {
number in String(number)
}
print(“numbersInString: (numbersInString)”)

Output:
It will produce the following output −
numbersInString: [“1”, “2”, “3”, “4”, “5”, “6”, “7”]

3. The compactMap() Function :
Iterating through the elements in an array, compactMap() returns an updated array only containing elements that satisfy the condition stated within its body. The array will be updated without any elements that result in a nil value. Or we can say that the compactMap() loops through all the elements in the array and returns non-nil values.

Example
Swift program to convert string array to an integer array using the comapctMap() function.

import Foundation
let numbersInString = [“1”, “x2”, “3”, “4”, nil, “five5”]
let validNumbers = numbersInString.compactMap {
stringValue in
Int(stringValue ?? “”)
}
print(“validNumbers: (validNumbers)”)

Output:
It will produce the following output −
validNumbers: [1, 3, 4]

4. The flatMap() Function :
The flatMap() function allows us to transform a set of arrays into a single set that contains all of the elements. It concatenates the elements of specified collections into a resultant collection.

Example
Swift program to convert a multi-dimensional array into a one-dimensional array using the flatMap() function.

import Foundation
let marks = [[3, 4, 5], [2, 5, 3], [1, 2, 2], [5, 5, 4], [3, 5, 3]]
let allMarks = marks.flatMap {
marksArray -> [Int] in
marksArray
}
print(“allMarks: (allMarks)”)

Output :
It will produce the following output −
allMarks: [3, 4, 5, 2, 5, 3, 1, 2, 2, 5, 5, 4, 3, 5, 3]

5. The filter() Function :
The filter() will iterate through all elements in an array and will return an updated array only with the elements that satisfy the condition written inside the body of the filter. It is an essential function. While you write code, many times you need to filter out collections to produce a filtered collection based on a condition.

The return type of the closure is a Bool value; items in the resulting array are those that satisfy the condition inside the body;

Example
Swift program to display only positive numbers from the given array using the filter() function.

import Foundation
let numbers = [-12, 23, -1, 56, 9, -2, 0, 14, 8]
let positives = numbers.filter {
number in
number > 0
}
print(“positives: (positives)”)

Output:
It will produce the following output −
positives: [23, 56, 9, 14, 8]

6. The reduce() Function :
The reduce() function will iterate through all elements in an array and return an object with the combined value of all elements.

Example
Swift program to find the sum of the array elements using the reduce() function.

import Foundation
let numbers = [1, 5, 2, 10, 6]
let sum = numbers.reduce(0) {
(result, number) -> Int in
result + number
}
print(“sum:”, sum)

Output:
It will produce the following output −
sum: 24