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
Category: Computer Programming
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
Swift – Dictionaries
Swift – Dictionaries ”; Previous Next 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](key:value) 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 − Using Subscript Syntax We can retrieve a value from a dictionary by using subscript syntax, passing the key of the value we want to retrieve within square brackets immediately after the name of the dictionary. Syntax Following is the syntax for accessing dictionaries − var someVar = someDict[key] Example import Foundation // Defining a dictionary var someDict:[Int:String] = [1:”One”, 2:”Two”, 3:”Three”] // Accessing the value of key = 1 using subscript syntax var someVar = someDict[1] // Checking if the value is not nil before using it if let result = someVar { print(“Value of key = 1 is (result)”) } else { print(“Value not found”) } Output It will produce the following output − Value of key = 1 is One Using keys Property We can access the key separately using the keys property. This property will return all the keys present in the dictionary. Syntax Following is the syntax for the keys property − dictionary.keys Example import Foundation // Defining a dictionary var someDict:[Int:String] = [1:”One”, 2:”Two”, 3:”Three”] // Accessing the keys var output = someDict.keys print(output) Output It will produce the following output − [1, 2, 3] Using values Property We can access the value separately using the values property. This property will return all the values present in the dictionary. Syntax Following is the syntax for values property − dictionary.values Example import Foundation // Defining a dictionary var someDict:[Int:String] = [1:”One”, 2:”Two”, 3:”Three”] // Accessing the values var output = someDict.values print(output) Output It will produce the following output − [“Two”, “One”, “Three”] 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) Example import Foundation // Declaring dictionary var someDict:[Int:String] = [1:”One”, 2:”Two”, 3:”Three”] print(“Original Dictionary:”, someDict) // Updating the value of key = 2 with new value // Using updateValue() function someDict.updateValue(“Four”, forKey: 2) // Displaying output print(“Updated Dictionary:”, someDict) Output It will produce the following output − Original Dictionary: [1: “One”, 2: “Two”, 3: “Three”] Updated Dictionary: [1: “One”, 2: “Four”, 3: “Three”] 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 Example import Foundation // Declaring dictionary var someDict:[Int:String] = [1:”One”, 2:”Two”, 3:”Three”] // Updating the value of key = 1 with new value someDict[1] = “New value of one” // Displaying
Swift – Comments
Swift – Comments ”; Previous Next 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. Or we can say that comments are non-executable text and they are like a note or reminder to the user or programmer. In Swift, we can define comments in three different ways − Single line comments Multi-line comments Nested Multi-line comments Single Line Comment in Swift A single-line comment is used to add only one-liner text in the code. A single-line comment begins with double forward slashes (//). The compiler or interpreter always ignores them and does not affect the execution of the program. Syntax Following is the syntax of single line comment − // Add your comment here Example Swift program to add a single-line comment. Here we add a single-line comment in the program to explain the working of the for-in loop. import Foundation let num = 7 let endNum = 10 // For loop to display a sequence of numbers for x in num…endNum{ print(x) } Output 7 8 9 10 Multi-Line Comment in Swift Multi-line comments are used to display multiple lines of non-executable text in the program to explain the working to the specific line of code or to add warnings, notes, etc. by the developers. Like other programming languages, in Swift, the multi-line comments begin with a forward slash followed by an asterisk(/*) and end with an asterisk followed by the forward-slash (*/). Syntax Following is the syntax of multi-line comment − /* Add your Mult-line comment here */ Example Swift program to add multi-line comments. Here we add multiple lines of comment in the program to explain how to add two arrays of the same length. import Foundation let arr1 = [1, 4, 6, 2] let arr2 = [3, 5, 2, 4] var result = [Int]() /* Check the length of the array. If they are equal then we add them using the + operator and store the sum in the result array */ if arr1.count == arr2.count { for i in 0..<arr1.count { let sum = arr1[i] + arr2[i] result.append(sum) } print(result) } else { print(“Arrays must of same length.”) } Output [4, 9, 8, 6] Nested Multi-Line Comment in Swift Starting from Swift 4 a new feature is also included in the multi-line comment that is nested multi-line comment. Now you are allowed to nest or add a multi-line comment inside another multi-line comment. It can easily comment out many blocks, even if the block contains multi-line comments. Syntax Following is the syntax of nested multi-line comments − /* Add your multi-line comment. /* Add your nested multi-line comment. */ End multi-line comment */ Example Swift program to add nested multi-line comments. Here we add nested multiple lines of comment in the program to add an alternative code of adding two arrays. import Foundation let arr1 = [1, 4, 6, 2] let arr2 = [3, 5, 2, 4] var result = [Int]() /* Checks the length of the array. If they are equal then we add them using the + operator and store the sum in the result array /*You can also use the following code to add two arrays: if arr1.count == arr2.count { let result = zip(arr1, arr2).map(+) print(result) */ */ if arr1.count == arr2.count { for i in 0..<arr1.count { let sum = arr1[i] + arr2[i] result.append(sum) } print(result) } else { print(“Arrays must of same length.”) } Output [4, 9, 8, 6] Print Page Previous Next Advertisements ”;
Swift – Function Overloading
Swift – Function Overloading ”; Previous Next A Function is a snippet of code that is used to perform a specific task. In Swift, we are allowed to overload functions. Function overloading is a technique in which we can create multiple same-name functions but with different parameters or argument labels. So when an overloaded function is called, the compiler determines which function should execute according to the number of parameters and types of parameters provided at the time of call. In Swift, we cannot overload functions according to the return type. We can overload functions in the following ways − Overloading with a different number of parameters. Overloading with different parameter types. Overloading with argument label. Overloading with Different Number of Parameters In function overloading with a different number of parameters, the names of the two or more functions are the same but the number of parameters is different. The functions can have the same or different names of parameters. In this type of function overloading, the function is invoked according to the number of parameters provided by the user during the function call. Example Swift program to demonstrate function overloading with a different number of parameters. import Foundation // Function 1 func product(num1: Int, num2: Int){ // Calculating product let result = num1 * num2 print(“Function 1: Product = “, result) } // Function 2 func product(num1: Int, num2: Int, num3: Int){ // Calculating product let result = num1 * num2 * num3 print(“Function 2: Product = “, result) } // Function 3 func product(num1: Int, num2: Int, num3: Int, num4: Int){ // Calculating product let result = num1 * num2 * num3 * num4 print(“Function 3: Product = “, result) } // Calling function 1 product(num1: 23, num2: 34) // Calling function 2 product(num1: 53, num2: 34, num3: 34) // Calling function 3 product(num1: 23, num2: 34, num3: 55, num4: 21) Output It will produce the following output − Function 1: Product = 782 Function 2: Product = 61268 Function 3: Product = 903210 Overloading with Different Parameter Types A function can be overloaded with different parameter types which means multiple functions contain the same name and number of parameters but the parameter types are different. In this type of function overloading, the function is invoked according to the type of parameters provided by the user during the function call. Example Swift program to add two strings using nested function. import Foundation // Function 1 func Addition(num1: Int, num2: Int){ // Adding two values let result = num1 + num2 print(“Function 1: Result = “, result) } // Function 2 func Addition(num1: String, num2: String){ // Adding two values let result = num1 + num2 print(“Function 2: Result = “, result) } // Calling function 1 Addition(num1: 23, num2: 34) // Calling function 2 Addition(num1: “Hello!”, num2: “Tutorialspoint”) Output It will produce the following output − Function 1: Result = 57 Function 2: Result = Hello!Tutorialspoint Overloading with Argument Label We can overload functions according to their argument labels. In such type of overloading, the function names are the same but the argument label is different. So that at the time of execution compiler can easily identify which function should it invoke. Example Swift program to overload function according to their argument labels. import Foundation // Function 1 func Area(length: Int, width: Int){ let result = length * width print(“Function 1: Result=”, result) } // Function 2 func Area(l: Int, w: Int){ let result = l * w print(“Function 2: Result=”, result) } // Calling function 1 Area(length: 23, width: 3) // Calling function 2 Area(l:13, w: 3) Output It will produce the following output − Function 1: Result= 69 Function 2: Result= 39 Advantages of Function Overloading in Swift The following are the advantages of function overloading − It improves the code readability. Reduce multiple function names by giving the same name to all the functions. It enhances type safety and reduces runtime errors. Print Page Previous Next Advertisements ”;