Swift – Subscripts ”; Previous Next Subscript is a special feature provided by Swift to access the element of a collection, sequence and list. It is the most convenient way to get or set values in the collection. We can also get or set values according to their index using subscripts. Even classes, structure and enumeration can define subscripts. A single type can have multiple subscripts. We can use the appropriate subscript to overload according to the type of index value passed to the subscript. We can define a subscript that can take single as well as multiple parameters according to our requirements. Subscript Declaration We can define subscript using the subscript keyword and can take one or more input parameters and return type. It can be read-write or read-only. It allows us to perform queries on the instance by writing one or more values in square brackets followed by the instance name. Syntax Following is the syntax of the subscript − subscript(index: Int) -> Int { get { // Retrieve the value at the specified index } set(newValue) { // Set the value at the specified index } } Following is the syntax of read-only subscript − subscript(index: Int) -> Int { // Return subscript value here } Example Swift program to retrieve values using subscript syntax. // Defining structure struct subexample { let decrementer: Int // Declaring subscript subscript(index: Int) -> Int { return decrementer / index } } // Creating instance of the structure let division = subexample(decrementer: 100) // Retrieving values using subscript syntax print(“The number is divisible by (division[9]) times”) print(“The number is divisible by (division[2]) times”) print(“The number is divisible by (division[3]) times”) print(“The number is divisible by (division[5]) times”) print(“The number is divisible by (division[7]) times”) Output It will produce the following output − The number is divisible by 11 times The number is divisible by 50 times The number is divisible by 33 times The number is divisible by 20 times The number is divisible by 14 times Example Swift program to access values using subscript syntax. // Defining class class daysofaweek { private var days = [“Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”] // Declaring subscript subscript(index: Int) -> String { // Retrieve the value at the specified index get { return days[index] } // Set the value at the specified index set(newValue) { self.days[index] = newValue } } } // Creating instance of class var p = daysofaweek() // Accessing elements using subscript print(p[0]) print(p[1]) print(p[2]) print(p[3]) Output It will produce the following output − Sunday Monday Tuesday Wednesday Options in Subscript Subscripts can take single or multiple input parameters of any data type and it can also return a value of any data type. These parameters can have default values. Subscripts can use variadic parameters but they cannot use in-out parameters. Defining multiple subscripts is termed as ”subscript overloading” where a class or structure can provide multiple subscript definitions as required. These multiple subscripts are inferred based on the types of values that are declared within the subscript braces. Example Swift program to access values using subscript syntax. // Defining structure struct Matrix { let rows: Int, columns: Int var print: [Double] // Initializer to create a matrix init(rows: Int, columns: Int) { self.rows = rows self.columns = columns // Initializing the matrix with an array print = Array(repeating: 0.0, count: rows * columns) } // Subscript for accessing and modifying elements in the matrix subscript(row: Int, column: Int) -> Double { get { return print[(row * columns) + column] } set { print[(row * columns) + column] = newValue } } } // Creating an instance var mat = Matrix(rows: 3, columns: 3) // Modifying elements in the matrix using subscript notation mat[0, 0] = 1.0 mat[0, 1] = 2.0 mat[1, 0] = 3.0 mat[1, 1] = 5.0 // Accessing and printing elements from the matrix using subscript notation print(“(mat[0, 0])”) print(“(mat[0, 1])”) print(“(mat[1, 0])”) print(“(mat[1, 1])”) Output It will produce the following output − 1.0 2.0 3.0 5.0 Print Page Previous Next Advertisements ”;
Category: swift
Swift – Arrays
Swift – Arrays ”; Previous Next 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. If you assign a created array to a variable, then it is always mutable, which means you can change it by adding, removing, or changing its elements; but if you assign an array to a constant, then that array is immutable, and its size and contents cannot be changed. If you try to change it, then the compiler will throw an error. 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) Example In the following example we are creating 3 different arrays using all the above discussed syntaxes − import Foundation // Defining an array by specifying the type var arr1:[Int] = [11, 44, 55, 77, 88, 22] print(“Contents of arr1 :”, arr1) // Defining an array without specifying the type var arr2 = [101, 404, 550, 770, 880, 222] print(“Contents of arr2 :”, arr2) // Defining an array with a single value var arr3 = Array(repeating: “Tutorialspoint”, count: 3) print(“Contents of arr3 :”, arr3) Output The above program produces the following result − Contents of arr1 : [11, 44, 55, 77, 88, 22] Contents of arr2 : [101, 404, 550, 770, 880, 222] Contents of arr3 : [“Tutorialspoint”, “Tutorialspoint”, “Tutorialspoint”] 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] Here, the index starts from 0 which means the first element can be accessed using the index as 0, the second element can be accessed using the index as 1 and so on. Example import Foundation // Defining and initializing an array var someArr:[Int] = [11, 44, 55, 77, 88, 22] // Accessing the element present at index 3 // Using subscript syntax print(“Array element:”, someArr[3]) Output When the above code is compiled and executed, it produces the following result − Array element: 77 Using subscript syntax, we can also modify the elements of the array by assigning new value to the existing index. Example import Foundation // Defining and initializing an array var someArr:[Int] = [11, 44, 55, 77, 88, 22] // Modifying the array element present at index 3 // Using subscript syntax someArr[3] = 33 print(“Modified Array element:”, someArr[3]) Output When the above code is compiled and executed, it produces the following result − Modified Array element: 33 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 It adds a new element at the end of the specified array. Example import Foundation // Defining and initializing an array var someArr:[Int] = [43, 32, 11] // Appending new element using append() method someArr.append(34) someArr.append(60) print(“Updated Array”, someArr) Output When the above code is compiled and executed, it produces the following result − Updated Array [43, 32, 11, 34, 60] Using the addition assignment operator (+=) We can also add a new item at the end of an array using the addition assignment operator. Example import Foundation // Defining and initializing an array var someArr:[Int] = [43, 32, 11] // Adding new element using += operator someArr += [30] someArr += [90] print(“Updated Array”, someArr) Output When the above code is compiled and executed, it produces the following result − Updated Array [43, 32, 11, 30, 90] 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 We can use a for-in loop to iterate over the entire set of values in an array. It is the easiest and cleanest method to access and process each element of the given array sequentially. 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) } Output When the above code is compiled and executed, it produces the following result − Array Elements: 3 56 12 4 23 5 6 7 8 Using the enumerated() function with for-in loop We can also use the
Swift – Comparison Operators
Swift – Comparison Operators ”; Previous Next Comparison Operator in Swift Comparison operators are the most frequently used operators in Swift. They are used to compare two values or expressions and return a boolean value accordingly. They are commonly used with loops and conditional statements. Swift supports the following comparison operators − Operator Name Example == Equal to 56 == 56 = true != Not Equal to 56 != 78 = true > Greater than 56 > 32 = true < Less than 44 < 67 = true >= Greater than or Equal to 77 >= 33 = true <= Less than or Equal to 21 <= 56 = true Equal to Operator in Swift The equal to operator is used to check if both the given values are equal or not. If they are equal, then it will return true. Otherwise, it will return false. Syntax Following is the syntax of the Equal to “==” operator − Value1 == Value2 Example Swift program to check if the input password is equal to the stored password using the equal to “==” operator. import Foundation let password = “XP123″ if (password == “XP123”){ print(“Welcome!! Entered password is correct”) } else { print(“Error!!! Please enter correct Password”) } Output Welcome!! Entered password is correct Not Equal to Operator in Swift The not equal to operator is used to check if both the given values are not equal. If they are not equal, then it will return true. Otherwise, it will return false. Syntax Following is the syntax of the not equal to operator − value1 != value2 Example Swift program to check if the input string is not equal to the stored string using the not equal to(!=) operator. import Foundation let str = “Mohina” if (str != “Noni”){ print(“Both the strings are not equal”) } else { print(“Both the strings are equal”) } Output Both the strings are not equal Greater than Operator in Swift The greater than operator is used to check if the left-hand side value is greater than the right-hand side value. If they are, then it will return true. Otherwise, it will return false. Syntax Following is the syntax of the Greater than operator − value1 > value2 Example Swift program to add only those numbers that are greater than 50 using greater than “>” operator. import Foundation let arr = [3, 55, 2, 44, 66] var sum = 0 // Iterate through each element of the array for x in arr{ // Find the sum of only those elements that // are greater than 50 if (x > 50){ sum += x } } print(“Sum = (sum)”) Output Sum = 121 Less than Operator in Swift The less than operator is used to check if the left-hand side value is less than the right-hand side value. If they are, then it will return true. Otherwise, it will return false. Syntax Following is the syntax of the Less than operator − value1 < value2 Example Swift program to add only those numbers that are less than 55 using less than(<) operator. import Foundation let arr = [1, 55, 2, 90, 12] var sum = 0 // Iterate through each element of the array for x in arr{ // Find the sum of only those elements that // are less than 55 if (x < 55){ sum += x } } print(“Sum = (sum)”) Output Sum = 15 Greater than or Equal to Operator in Swift The greater than or equal to operator is used to check if the left-hand side value is greater than or equal to the right-hand side value. If they are, then it will return true. Otherwise, it will return false. Syntax Following is the syntax of the Greater than or Equal to operator − value1 >= value2 Example Swift program to check valid age for voting using greater than or equal to(>=) operator. import Foundation let age = 18 if (age >= 18){ print(“You are eligible for voting”) } else { print(“You are not eligible for voting”) } Output You are eligible for voting Less than or Equal to Operator in Swift The less than or equal to operator is used to check if the left-hand side value is less than or equal to the right-hand side value. If they are, then it will return true. Syntax Following is the syntax of the Less than or Equal to operator − value1 <= value2 Example Swift program to compare two numbers using less than or equal to operator. import Foundation let num = 18 if (num <= 20){ print(“Given num is less than 20”) } else { print(“Given num is greater than 20″) } Output Given num is less than 20 swift_operators.htm Print Page Previous Next Advertisements ”;
Swift – Enumerations
Swift – Enumerations ”; Previous Next An enumeration is a user-defined data type that consists of a group of related values and provides a way to work with those values in a type-safe manner. Enumeration generally does not provide value to each case but if you want to you can assign value to each enumeration case and the value can be of any type such as string, int, float, or character. Enumeration in Swift We can define enumeration using the enum keyword followed by the name and curly braces, where the curly braces contain the enumeration cases using the case keyword. The enumeration name should start with a capital letter (Ex: enum DaysofaWeek). Syntax Following is the syntax of the enumeration − enum EnumName { // enumeration cases case value1 case value2 … case valueN } We can also define multiple enumeration cases into a single line, where each case is separated by commas. enum EnumName { // enumeration cases case value1, value2, value3,…,valueN } Example Following Swift”s example to demonstrate how to create an enum − enum CarColor { // enum values case Blue case Green case White case Off-white } Creating Variable of Enumeration in Swift In enumeration, we can directly create a variable of enumeration type and assign a case to it. We can assign a case to an enum variable using dot(.) notation, where dot notation is followed by the value(for example: .value). Syntax Following is the syntax for creating an enum variable − var variableName : EnumName Following is the syntax for assigning a value to an enum variable − variableName = .enumValue Example Swift program to create and access an enum variable. // Defining an enumeration with cases representing subjects enum Subjects { case Maths case Science case Social case English case Hindi case ComputerProgramming } // Creating and assigning value to an enum variable var name: Subjects = .English // Access the value of the enum variable and display data accordingly switch name { case .English, .Hindi, .ComputerProgramming: print(“Elective subjects!”) case .Maths, .Science, .Social: print(“Compulsory subjects”) } Output It will produce the following output − Elective subjects! Example Swift program to create and access an enum variable. // Defining an enumeration with cases representing car colour enum Subjects { case Black case Blue case MidnightGray case White case OffWhite case Silver } // Creating and assigning value to an enum variable var color: Subjects = .Blue // Using an if statement to check the enum value if color == .Blue { print(“Dark edition of car”) } Output It will produce the following output − Dark edition of car Enumeration with Raw Values in Swift In enumeration, we can also assign values to the enum cases and these values are known as raw values. Raw values can be strings, characters, or any of the integer or floating-point number types. Each raw value must be unique within its enumeration declaration and of the same type. Syntax Following is the syntax for assigning raw values to the enum cases − enum enumName : Type{ // enum values case value1 = RawValue1 case value2 = RawValue2 } Accessing Raw Values We can access raw values with the help of a pre-defined property named rawValue. The rawValue property is used to retrieve the raw value associated with the specified enum case. Syntax Following is the syntax of the rawValue property − let variableName = enumName.enumCase.rawValue Example Swift program to access raw values of enumeration using rawValue property. // Defining an enumeration with cases representing car colour enum CarColor : Int { case Black = 2 case Blue = 4 case OffWhite = 5 case Silver = 6 } // Accessing the raw value var colorCount = CarColor.Blue.rawValue // Displaying the raw values print(“Raw Value:”, colorCount) Output It will produce the following output − Raw Value: 4 Implicitly Assigning Raw Values When integers or strings are used as raw values for enum cases, then it is not necessary to specify values for each enum case because Swift will automatically assign values for each enum case. Such type of method is known as implicitly assigning raw values. When we use Integer type as a raw value for enum cases and provide a raw value to the first case, then Swift will automatically assign raw values to the subsequent cases where the assigned value to the current case is greater than the previous case. Example Swift program to implicitly assign raw values of Integer type. // Defining an enumeration with cases representing marks subject enum SubjectMarks: Int { // Assigning raw value to the first case // Now Swift will automatically assign raw values to the cases // for english = 41, hindi = 42, and physics = 43 case maths = 40, english, hindi, physics } // Accessing the raw value let marks = SubjectMarks.hindi.rawValue print(“Marks of hindi = “, marks) Output It will produce the following output − Marks of hindi = 42 If we do not assign raw value to the first case, then by default Swift will assign zero to the first case and then 1 to the second case, 2 to the third case and so on. Example // Defining an enumeration with cases representing marks subject enum SubjectMarks: Int { // Here we do not assign raw value to the first case // So Swift will automatically assign default raw values case maths // Default raw value = 0 case english
Swift – Recursion
Swift – Recursion ”; Previous Next Recursion in Swift 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. Syntax Following is the syntax of the recursive function − func functionName(){ // body functionName() } functionName() Working of Recursion in Swift If we call a function within itself, it is known as a recursive function. Swift supports recursion in functions. Let”s understand the working of the recursion with the help of an example. Example Swift program to find the factorial of the given number using recursion − import Foundation // Function to find the factorial of the specified number func factorial(number: Int) -> Int { // Base condition if number == 0 || number == 1 { return 1 } else { // Recursive call with modified parameters return number * factorial(number:number – 1) } } let num = 4 let output = factorial(number: num) print(“Factorial of (num) is: (output)”) Output It will produce the following output − Factorial of 4 is: 24 In the above code, we have a recursive function named factorial(). So the working of this function is − 1st function call with 4: factorial(4) = 4 * factorial(3) 2nd function call with 3: factorial(3) = 3 * factorial(2) 3rd function call with 2: factorial(2) = 2 * factorial(1) 4th function call with 1: factorial(1) = 1(Here the value meets the base condition and the recursive call terminated) Returned from 4th function call: 1 * 1 = 1 Returned from 3rd function call: 2 * 1 = 2 Returned from 2nd function call: 3 * 2 = 6 Returned from 1st function call: 4 * 6 = 24 Hence the factorial of 4 is 24. Example Swift program to find the index of the specified element using binary search − import Foundation // Function to find a number from the given array using binary search func binarySearchAlgorithm(_ arr: [Int], num: Int, leftNum: Int, rightNum: Int) -> Int? { if leftNum > rightNum { return nil } let midValue = leftNum + (rightNum – leftNum) / 2 if arr[midValue] == num { return midValue } else if arr[midValue] < num { return binarySearchAlgorithm(arr, num: num, leftNum: midValue + 1, rightNum: rightNum) } else { return binarySearchAlgorithm(arr, num: num, leftNum: leftNum, rightNum: midValue – 1) } } let myArray = [11, 12, 13, 14, 15, 16, 17, 18, 19] if let resIndex = binarySearchAlgorithm(myArray, num: 16, leftNum: 0, rightNum: myArray.count – 1) { print(“Element found at index (resIndex)”) } else { print(“Element Not found”) } Output It will produce the following output − Element found at index 5 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. Advantages and Disadvantages of Recursion The following are the advantages of recursion − Recursive functions are easy to debug because each recursive call focuses on a small part of the task which allows more target testing and debugging. Recursive functions generally use parallel processing which improves their performance. Recursive solutions are much more readable and easy to maintain. Recursive functions are flexible and allow abstraction. The following are the disadvantages of Recursion − While working with a more complex problem, the execution flow of the recursion is difficult to track. It has more overhead than iterative loops. If we do not provide the correct base condition, it will lead to infinite recursion. Recursion is not best suitable for all types of problems some problems are better to solve with the iteration method. Print Page Previous Next Advertisements ”;
Swift – Structures
Swift – Structures ”; Previous Next The structure is the most commonly used user-defined data type. It allows us to group the related data and operations into a single block. It is useful for encapsulating the data and the functionality into a single unit and provides more organized and readable code. In a structure, we can add functionality with the help of methods and properties. In Swift, a structure does not require any extra file or interface for implementation, we can define a structure into a single file and the external interface accesses this code automatically. Structure is a value type. Structure in Swift Just like other programming languages in Swift, a structure is defined using a struct keyword along with a name and curly braces({}). Here the name must start with a capital letter such as School, not school. The curly braces contain all the properties and methods. Properties − The constants and variables associated with the structure are known as the properties of the structure. They are commonly used to store and retrieve values in the instance of the structure. A structure can have multiple properties. Methods − Functions associated with the structure are known as the methods of the structure. They are commonly used to define behaviour associated with the structure. Methods can have parameters and return values. A structure can have multiple methods. In Swift, using methods we are not allowed to change the properties. But if we want to change the properties inside the method, then we have to mark that method using a mutating keyword. Syntax Following is the syntax of the structure − struct nameStruct { // Properties Property 1 : Type Property 2 : Type // Methods func functionName(){ // Statement } // Mutating method mutating func functionName(){ // Statement } } Example In the following Swift example, we need to access the student”s record containing marks for three subjects and find out the total of three subjects. So, we create a structure named markStruct with three marks as datatype ”Int”. struct MarkStruct{ var mark1: Int var mark2: Int var mark3: Int } Swift Structure Instance A structure instance is an object that is created from the structure’s definition and represents some set of values for the properties. A single structure can have multiple instances and they are independent of each other, which means if we modify one instance that doesn”t affect other instances. We can create an instance of the structure by calling the structure initializer. A structure may or may not contain an initializer. So if a structure does not contain any initializer, then Swift will automatically receive a memberwise initializer to create a structure object. Using this initializer we can initialize each property by passing the initial value along with the name in the memberwise initializer. Syntax Following is the syntax of the structure instance − var objectName = StructName(propertyName1: value, propertyName2: value) Example In the following Swift example, we will create an instance of MarkStruct. struct MarkStruct{ var mark1: Int var mark2: Int var mark3: Int } // Creating instance using memberwise initializer var myObj = MarkStruct(mark1: 10, mark2: 20, mark3: 30) We can also create a structure’s instance without providing parameters or initial values if the structure contains a default initializer. struct MarkStruct{ var mark1: Int var mark2: Int var mark3: Int // Default initialzer init(){ Mark1 = 1 Marks2 = 2 Mark3 = 3 } } // Creating instance using default initializer var myInstance = MarkStruct() Accessing the Properties of the Structure in Swift To access the properties of the structure we can use a structure instance followed by a dot(.) and a property name. Using this notation we can also modify the values of the properties. With the help of this notation, we can also access and modify the sub-properties of the structure. Syntax Following is the syntax for accessing the properties of the structure − structInstanceName.PropertyName Following is the syntax for modifying the properties of the structure − structInstanceName.PropertyName = value Following is the syntax for accessing the sub-properties of the structure − structInstanceName.PropertyName.subPropertyName Following is the syntax for modifying the sub-properties of the structure − structInstanceName.PropertyName.subPropertyName = value Example Swift program to access and modify the properties of the structure. // Defining a structure struct Employee { var name: String var age: Int var department: String var salary: Int } // Creating an instance of the Employee structure // with initial values of the properties var emp = Employee(name: “Mona”, age: 22, department: “HR”, salary: 32000) // Accessing the values of the properties using dot notation print(“Employee Details:”) print(“Name: (emp.name)”) print(“Age: (emp.age)”) print(“Department: (emp.department)”) print(“Salary: (emp.salary)”) // Modifying the values of the properties using dot notation emp.age = 23 emp.salary = 33000 // Displaying the updated values print(“nUpdated Values:”) print(“Age: (emp.age)”) print(“Salary: (emp.salary)”) Output It will produce the following output − Employee Details: Name: Mona Age: 22 Department: HR Salary: 32000 Updated Values: Age: 23 Salary: 33000 Example Swift program to access and modify the sub-properties of the structure. // Defining a structure with sub-properties struct Address { var buildingName: String var city: String var pincode: String } // Defining a structure struct Student { var name: String var age: Int var address: Address } // Creating an instance of the Student structure // with initial values of the properties var stud = Student(name: “Sumit”, age: 22, address: Address(buildingName: “Anad Vihar”, city: “Delhi”, pincode: “333333”)) // Accessing the values of the properties and sub-properties using dot notation print(“Student Details:”) print(“Name: (stud.name)”) print(“Age:
Swift-Escaping and Non-escaping closure ”; Previous Next Swift Closure Just like another programming language Swift also supports Closure. A closure is a self-contained block of functionality that can passed around and used inside the code to perform any specific task. It can assigned to a variable or can be passed as a parameter to a function. A closure can capture values from its surrounding context and can be used as a callback or inline code. Swift supports the following type of closure − Escaping Closure Non-Escaping Closure Let us discuss both of them in detail. Escaping Closures in Swift When a closure is passed as an argument to the function but that closure is called after the function returns, then such type of closure is known as escaping closure. By default, the closure passed in the function as a parameter is a non-escaping parameter, which means the closure will execute during the execution of the function. To declare a closure as an escaping closure we have to use the @escaping keyword before the parameter type that represents the escaping closure. Syntax Following is the syntax for escaping closure − func methodname(closure: @escaping() -> Void){ // body // Calling the closure closure() } Example Swift program to demonstrate escaping closure. import Foundation class Operation{ // Method that takes two numbers and an escaping closure to find their product func product(_ x: Int, _ y: Int, productResult: @escaping (Int) -> Void) { // Activating an asynchronous task DispatchQueue.global().async { let output = x * y // Calling escaping closure productResult(output) } } } // Creating object of Operation class let obj = Operation() // Accessing the method obj.product(10, 4) { res in print(“Product of 10 * 4 = (res)”) } // Activating the passage of time DispatchQueue.main.asyncAfter(deadline: .now() + 2) { // It will be executed after a delay, simulating an asynchronous operation } Output It will produce the following output − Product of 10 * 4 = 40 Non-Escaping Closure in Swift Non-escaping closures are the default in Swift, we do not require any special notation to represent non-escaping closures. Such type of closure executes during the execution of the function in which they are passed, once the execution of the function ends the closure is no longer available for execution. They are not stored for later execution. Syntax Following is the syntax of non-escaping closure − mutating func methodname(Parameters) -> returntype { Statement } Example Swift program to demonstrate non-escaping closure. class Operation { // Function that takes two numbers and a non-escaping closure to calculate their sum func sum(_ X: Int, _ Y: Int, add: (Int) -> Void) { let result = X + Y // Calling the non-escaping closure add(result) } } // Creating the object of operation class let obj = Operation() obj.sum(10, 12) { add in print(“sum: (add)”) } Output It will produce the following output − Sum: 22 Escaping VS Non-Escaping Closure Following are the major differences between the escaping and non-escaping closures − Escaping Closure Non-Escaping Closure It can outlive the function in which it is passed. It executes during the execution of the function. It can store as a property or can assigned to a variable. It cannot stored and not allowed to used outside the function’s scope. It is commonly used for asynchronous operations like network request, etc. It is commonly used for synchronous operations like simple computation, etc. @escaping keyword is used to created escaping clousre. It is by default closure and doesnot required any special syntax. Print Page Previous Next Advertisements ”;
Swift – Higher-Order Functions ”; Previous Next 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 but don”t worry you don”t need to be a master of closure. They are easy to use and also reduce the size of the code in the project and can be reusable. 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. Syntax Following is the syntax of the forEach() function − func forEach(_x: (Self.Element)throws-> Void) rethrows Parameter x represents a closure that takes an item of the given sequence as a parameter. 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 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). Syntax Following is the syntax of the map() function − func map<T>(_ mTransform: (Self.Element) throws -> T) rethrows -> [T] Parameter The mTransform is a mapping closure. It accepts elements from the given sequence and returns a transformed value of the same or different type. Return Value It will return a transformed array. 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”] 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. Syntax Following is the syntax of the compactMap() function − Func compactMap<ElementOfResult>(_ mTransform: (Self.Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult] Parameter The mTransform is a closure. It accepts elements from the given sequence and returns an optional value. Return Value It will return a transformed array of 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] 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. Syntax Following is the syntax of the flatMap() function − func map<SegmentOfResult>(_ mTransform: (Self.Element) throws -> SegmentOfResult) rethrows -> [SegmentOfResult.Element] where SegmentOfResult : Sequence Parameter The mTransform is a closure. It accepts elements from the given sequence and returns a sequence. Return Value It will return a flattened array. 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] 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; Syntax Following is the syntax of the filter() function − func filter(_ resultantCollection: (Self.Element) throws -> Bool) rethrows -> Self Parameter The resultantCollection is a closure. It accepts elements from the given sequence and returns a boolean value which indicates whether the element should included in the resultant collection or not. Return Value It will return a collection that contains only those items 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,
Swift – Functions
Swift – Functions ”; Previous Next 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. Function Definition in Swift 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 } Example Swift program to demonstrate how to create a function. // Function with return type func student(name: String) -> String { return name } print(student(name: “First Program”)) print(student(name:”About Functions”)) Output It will produce the following output − First Program About Functions Calling a Function in Swift Calling a function means executing the set of statements present inside the function. We can call a function through its name and at the time of calling it is necessary to provide all the arguments (if available). Let us suppose we defined a function called ”display” to Consider for example to display the numbers a function with function name ”display” is initialized first with argument ”no1” which holds integer data type. Then the argument ”no1” is assigned to argument ”a” which hereafter will point to the same data type integer. Now the argument ”a” is returned to the function. Here display() function will hold the integer value and return the integer values every time the function is invoked. Syntax Following is the syntax for calling a function − funcName(parameters) Example Swift program to demonstrate how to call a function. // Creating function func display(no1: Int) -> Int { let a = no1 return a } // Calling function print(display(no1: 100)) print(display(no1: 200)) Output It will produce the following output − 100 200 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. Or they allow us to pass values to the function at the time of calling and can perform operations on those values. They are always specified inside the function along with the label, type and value(if available). Swift function supports the following types of parameters − Regular Parameters Varadic Parameters In-Out parameters Let us discuss all types of parameters in detail. Regular Parameters Regular parameters are the most commonly used parameters in the function. They allow us to perform basic operations according to the specified value. A function can have a single or multiple regular parameters. Each regular parameter has its argument label, and explicit type and they are separated by comma. We can also specify the default value in the regular parameter, which means if we omit that parameter while calling that function, then the default value present in that parameter will used. Syntax Following is the syntax for regular parameters − func funcname(name1: Type, name2:Type = defualtValue) -> returntype { Statement return value } Example Swift program to demonstrate how to create a function with regular parameters. // Creating function with regular parameters and default value func Sum(num1: Int, num2: Int = 2) -> Int { var result = 0 result = num1 + num2 return result } // Calling function print(“Sum 1:”, Sum(num1: 10)) print(“Sum 2:”, Sum(num1: 20, num2: 12)) Output It will produce the following output − Sum 1: 12 Sum 2: 32 Variadic 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. A single function can contain multiple variadic parameters and after the first variadic parameter, the next variadic parameters must contain argument labels to distinguish them. The values passed inside the variadic parameters are available as an array in the function. A variadic parameter is not marked as inout. Syntax Following is the syntax for variadic parameters − func funcname(_name1: Type…, name2:Type…, name3: Type…) -> returntype { Statement return value } Example Swift program to demonstrate how to create a function with varadic parameters. // Creating function with variadic parameter func Product(_ num: Int…) -> Int { var result = 1 for x in num{ result *= x } return result } // Calling function and passing multiple values of the same type print(“Product:”, Product(10, 20, 30)) Output
Swift – Closures
Swift – Closures ”; Previous Next What is Closures in Swift? Closures are self-contained blocks of functionalities that can be used inside the program and perform the specified task. Closures are similar to blocks in Objective-C or anonymous functions in other programming languages. They are allowed to capture and store the references to the variables or constants from the context in which they are defined. Also, they can access the values of these constants or variables even if they are outside the original scope. Closure in the Swift has three forms − Global Functions − They are closures with a name that do not capture any value. Nested Function − A function defined inside another function. They have names and can capture values from the enclosing function. Closure Expression − Using this we can write closure more concisely. We can write unnamed closures that capture values from the adjacent block. Closures Expression Closure expression provides a way to write inline closure or inline and unnamed functions. It supports various short, optimized and focused syntaxes to write closure without losing its clarity. So first of all we will see the basic syntax of closure then we will move to the other expression syntaxes supported by Swift − Inferring parameter and return value types from context. Implicit returns from single-expression closures. Shorthand argument names Operator methods Defining and Calling basic closure In Swift, we can define a closure simply by using curly braces{}. These curly braces contain the closure parameters, return type(if available), the in keyword to separate the parameter and return type with the body, and the body of the closure. The parameters of closure can be regular, in-out and variadic parameters, but they do not contain default values. Tuples can also used as a parameter and return types in closures. And we can call a closure by passing value for the parameters(if available). Syntax Following is a generic syntax to define closure which accepts parameters and returns a data type − {(parameters) -> return type in // body of closure } Following is the syntax for calling the closure. closure(parameters) Example Swift program to demonstrate a closure without parameters. // Creating a Closure let studname = { print(“Welcome to Swift 4 Closures”) } // Calling a closure studname() Output It will produce the following output − Welcome to Swift 4 Closures Example Swift program to demonstrate a closure with parameters. // Closure with parameters let divide = {(val1: Int, val2: Int) -> Int in return val1 / val2 } // Calling closure let result = divide(200, 20) print (result) Output It will produce the following output − 10 Inferring type from context A closure can also pass as an inline closure expression in the function or method, so we are allowed to infer the types of its parameters and the return value. That means we are not explicitly required to write the type of parameter passed in the closure and the type of value returned by the closure, the compiler will automatically infer the type of the closure from the context in which it is used. Example Swift program to pass a closure as a parameter in the function. // Define an array of String let myValues = [“Mohina”, “Suman”, “Mohit”] // Use the ”map” function to add the given string in all the elements of the array /* The type of closure is inferred according to the fact that ”map()” is applied to an array of strings. So here the closure adds a specified string to each element hence the inferred type of the closure is (String) -> String*/ let newArray = myValues.map { $0 + ” Hey” } print(newArray) Output It will produce the following output − [“Mohina Hey”, “Suman Hey”, “Mohit Hey”] Implicit Return From Single-Expression Closure In Closure, a single expression can implicitly return an expression without explicitly using the return keyword. Or we can say that a closure can return an expression without specifying the return type if it contains only one statement. It makes syntax more straightforward and readable. Example Swift program to implicitly return expression from single expression closure. // Single line closure without return type let add: (Int, Int) -> Int = { a, b in a + b } let output = add(5, 6) print(“Addition:”, output) Output It will produce the following output − Addition: 11 Shorthand Argument Names While working with inline closure we are allowed to write the values of the closure”s arguments by the names $0, $1, $2, and so on, instead of naming them. It is the shortest way to express arguments in the closer. Where $0 refers to the first parameter, $1 refers to the second parameter, $2 refers to the third parameter and so on. If we are using these shorthand argument names, then we can remove the closure argument list from the definition section. The compiler will automatically infer the type of the arguments from the expected function type. We can also remove in keyword because the shorthand argument is defined in the expression body. Example Swift program to demonstrate shorthand argument names in closure. // Creating a closure var shorthand: (String, String) -> String // Assigning the second parameter and discarding the first parameter shorthand = { $1 } // Calling the closure with two arguments will return the second parameter print(shorthand(“100”, “200”)) Output It will produce the following output − 200 Operators Methods Swift provides an easy way