Swift – if statement

Swift – If Statement ”; Previous Next An if statement consists of a Boolean expression followed by a block of statements. When the boolean expression is true, then only the block of statements will execute. Otherwise, the controls move to the next statement present just after the if statement block. They are also known as branch statements because they allow the program to take different paths according to the given condition. For example, a teacher says to its students that “they are only allowed to write with a black pencil”. So here the conditional statement is “black pencil”. Hence If the “black pencil = true”, then only students are allowed to write. Syntax Following is the syntax of the if statement − if boolean_expression{ /* statement(s) will execute if the boolean expression is true */ } If the Boolean expression evaluates to true, then the block of code inside the if statement will be executed. If the Boolean expression evaluates to false, then the first set of code after the end of the if statement (after the closing curly brace) will be executed. Flow Diagram The following flow diagram will show how if-statement works − Example Swift program to check if the given number is less than 20 or not using the if statement. import Foundation var varA:Int = 10; /* Check the boolean condition using the if statement */ if varA < 20 { /* If the condition is true then print the following */ print(“varA is less than 20”); } print(“Value of variable varA is (varA)”); Output It will produce the following output − varA is less than 20 The value of variable varA is 10 Example Swift program to find the age for voting using if statement. import Foundation var age : Int = 19; /* Checking the age for voting */ if age >= 18 { /* If the condition is true */ print(“Eligible for voting”); } print(“A Candidate whose age is 18+ is eligible for voting “) Output It will produce the following output − Eligible for voting A candidate whose age is 18+ is eligible for voting Example Swift program to check the entered username is equal to the stored username using if statement. import Foundation let username = “input231″ let inputUsername = “input231″ // Checking for equality if username == inputUsername{ print(“Login successful”) } var result = 32 + 23 print(result) Output It will produce the following output − Login successful 55 Print Page Previous Next Advertisements ”;

Swift – Tuples

Swift – Tuples ”; Previous Next Tuples are used to store a group of values in a single value, for example (32, “Swift Programming”) is a tuple with two values that are 23 and “Swift Programming”. Tuples can store multiple values and each value is separated by a comma. It can store values of the same or different data types. They are helpful when we want to return multiple values together. Tuples are commonly used by the functions to return multiple values at the same time. Tuples are not used for complex data structures; they are useful for simple groups of related data. Syntax Following is the syntax of the Tuple − var myValue = (value1, value2, value3, value4, …, valueN) We can access the elements of the tuple with the help of dot notation followed by the element’s index − var result = tupleName.indexValue Example Swift program to create and access the elements of the tuple. import Foundation // Creating a tuple var myTuple = (“Romin”, 321, “Delhi”) // Accessing the elements of Tuple var name = myTuple.0 var id = myTuple.1 var city = myTuple.2 // Displaying the result print(“Employee name =”, name) print(“Employee id =”, id) print(“Employee city =”, city) Output Employee name = Romin Employee id = 321 Employee city = Delhi Tuple with different Data types In a tuple, we are allowed to store data of different types like (Int, Int, Float), (Float, Double, String), etc. You can also store data of the same data type like (Int, Int, Int), etc. Example Swift program to create a tuple of different data types. import Foundation // Creating a tuple with data of different data types var myTuple = (“Mona”, 21, “Mumbai”, 101) // Accessing the elements of Tuple var name = myTuple.0 var age = myTuple.1 var city = myTuple.2 var id = myTuple.3 // Displaying the result print(“Student name =”, name) print(“Student age =”, age) print(“Student city =”, city) print(“Student id =”, id) Output Student name = Mona Student age = 21 Student city = Mumbai Student id = 101 Assigning Tuple to Separate Variables We can assign the value of a tuple to a separate constant or variable so that we can access them using the name of that constant or the variable. Here the count of the constant or variable should be equal to the tuple’s values. Syntax Following is the syntax of assigning tuple values to a separate constant or variable − let (name1, name2) = tuple Example Swift program to create a tuple whose values are assigned to a set of constants. import Foundation // Creating a tuple var myTuple = (“Mickey”, 21, “Pune”) // Assigning tuple to a set of constants let(name, age, city) = myTuple // Accessing the value of tuples according to the constant print(“Student name =”, name) print(“Student age =”, age) print(“Student city =”, city) Output Student name = Mickey Student age = 21 Student city = Pune Tuple with Underscore in Swift We are allowed to use an underscore “_” with a tuple. It will ignore the part of the tuple with an underscore while decomposing the tuple. Or in other words, we can say that by using underscore we can ignore some tuple’s values. We are allowed to use multiple underscores with the same tuple to ignore multiple values. Syntax Following is the syntax of a tuple with an underscore − let (name1, name2, _) = tuple Example Swift program to create a tuple with underscore “_”. import Foundation // Creating a tuple var myTuple = (21, “Pune”, “CSE”) // Assigning a tuple to a set of constants let(age, _, branch) = myTuple // Accessing the values of tuples print(“Student age =”, age) print(“branch =”, branch) Output Student age = 21 branch = CSE Assigning Names to Individual Values in a Tuple In Swift, we are allowed to assign names to the individual elements of the tuple. We can also access the tuple’s elements according to their names. Syntax Following is the syntax for assigning names to a tuple’s elements − let myTuple = (id: 102, name: “Sona”) Example Swift program to create and access tuple elements according to their names. import Foundation // Creating a tuple var myTuple = (name: “Mona”, branch: “ECE”, year: 2022) // Accessing the values of tuples according to their names print(“Student name =”, myTuple.name) print(“Branch =”, myTuple.branch) print(“Current Year”, myTuple.year) Output Student name = Mona Branch = ECE Current Year 2022 Print Page Previous Next Advertisements ”;

Swift – Useful Resources

Swift – Useful Resources ”; Previous Next The following resources contain additional information on Swift. Please use them to get more in-depth knowledge on this topic. Useful Video Courses Swift 4 Online Training 39 Lectures 1 hours Tutorialspoint More Detail Swift Beginners Course: Learn to Code from Scratch 14 Lectures 2 hours Three Millennials More Detail Swift Online Course – Ultimate Guide To Mac and iOS Development 23 Lectures 1 hours Frahaan Hussain More Detail iOS Native XCUITEST (UITest) automation using Swift & Xcode 13 Lectures 39 mins Devasena Rajendran More Detail Basic Swift Code for iOS Apps 41 Lectures 2.5 hours Grant Klimaytys More Detail iOS 11 & Swift 4: From Beginner to Paid Professional™ 181 Lectures 43 hours YouAccel More Detail Print Page Previous Next Advertisements ”;

Swift – Type Casting

Swift – Type Casting ”; Previous Next What is Type Casting in Swift? Type casting is a special feature in Swift, which is used to check the type of the instance or change the type of instance from a class, structure or enumeration to another class, structure or enumeration. It is important because it allows run-time type checking and safe downcasting of instances to subclass types. Swift supports two operators: is and as. The ‘is’ operator is used to check the type of a value and ”as” is used to cast the type value to a different type. Type casting also checks whether the instance type follows a particular protocol conformance standard. Swift supports two types of type casting − Upcasting Downcasting Upcasting in Swift The process of casting an instance of subclass into its base class type is known as upcasting. Or we can say that upcasting is a process in which we treat the instance of a derived class as an instance of its base class. With the help of upcasting, we can only call the methods and properties of the superclass. After upcasting we are not allowed to directly call the methods or properties of the subclass, if you try to do you will get an error. In Swift, upcasting is implicit means we don”t require any special syntax for upcasting, we can directly cast the instance of subclass as the instance of superclass. It is safe to use directly because the instance of the subclass is always treated as the instance of the superclass. Upcasting is commonly used while we are working with polymorphic code or when we want to treat an instance of a different type as the instance of its common base type. Example Swift program for upcasting the instance of the subclass as the instance of the superclass. // Base class class Shape { func display(){ print(“Ball is in the shape of sphere”) } } // Sub class class Rectangle: Shape { func show(){ print(“Rectangle is the most commonly used shape”) } } // Creating an instance of the Rectangle class let rect = Rectangle() // Upcasting the instance of the rectangle class as the instance of the Shape class let obj : Shape = rect // Accessing the method of superclass obj.display() // Now we are not able to directly access the method or properties of the sub-class // If we do we will get an error // obj.show() Output It will produce the following output − Ball is in the shape of sphere Downcasting in Swift The process of casting an instance of a superclass type into a subclass type is known s downcasting. Or we can say that downcasting is a process in which we treat the instance of the base class as an instance of the derived class. It is not necessary that downcasting is always successful, it can be a failure. Swift supports two types of downcasting − Conditional Downcasting(as?) Forced Downcasting(as!) Let”s discuss both of them in detail Conditional Downcasting(as?) The conditional downcasting (as?) operator is used to downcast an instance of the superclass type to a specific subclass type. This operator will return an optional containing the instance of the subclass when the downcast is successful. When the downcast is unsuccessful, then this operator will return nil. This operator is generally used when we are not sure whether the downcast will be a success or not. Syntax Following is the syntax of the conditional downcasting operator(as?) − if let constName = instance as? Type { // Statement that will execute when downcast is successful } else { // Statement that will execute when downcast is unsuccessful } Example Swift program to demonstrate the use of conditional downcasting operator(as?). // Base Class class ProgrammingLanguage { func show() { print(“Welcome to the great world of learning”) } } // Subclass class Swift: ProgrammingLanguage { func display() { print(“Welcome to Swift tutorial”) } } let obj: ProgrammingLanguage = Swift() // Here the conditional downcasting will be successful if let result1 = obj as? Swift { print(“Downcast is successful!”) // Accessing subclass method result1.display() } else { print(“Downcast is unsuccessful”) } // Here the conditional downcasting will be unsuccessful let newObj: ProgrammingLanguage = ProgrammingLanguage() if let result2 = newObj as? Swift { print(“nDowncast is successful!”) result2.display() } else { print(“Downcast is unsuccessful”) } Output It will produce the following output − Downcast is successful! Welcome to Swift tutorial Downcast is unsuccessful Forced Downcasting(as!) The forced downcasting (as!) operator is used to forcefully downcast an instance to a given subclass type. This operator will return an instance of the subclass. If the downcast is unsuccessful, then it will give a runtime error. This operator is generally used when we are sure that downcast will be a success. Syntax Following is the syntax for forced downcasting(as!) − let constantName = instance as! type Example Swift program to demonstrate the use of forced downcasting operator(as!). // Base Class class ProgrammingLanguage { func show() { print(“Welcome to the great world of learning”) } } // Subclass class Swift: ProgrammingLanguage { func display() { print(“Welcome to Swift tutorial”) } } let obj: ProgrammingLanguage = Swift() // Here the forced downcasting will be successful let res1 = obj as! Swift // Accessing the method of Swift class res1.display() // Here the forced downcasting will be successful so we will get an error /*let newobj: ProgrammingLanguage = ProgrammingLanguage() let res2 = newobj as! Swift res2.display()*/ Output It will produce the following output − Welcome to Swift tutorial Type Checking In

Swift – Generics

Swift – Generics ”; Previous Next Swift provides a special feature known as ‘Generic” to write flexible and reusable functions and types that can work well with any other type. Generics are used to avoid duplication and to provide abstraction. Swift has some standard libraries that are built with generics code. Arrays and dictionary types belong to a generic collection. So, we are allowed to create an array that holds a String value or can able to create an array that holds an int value. Similarly, for the dictionary. Example func exchange(inout a: Int, inout b: Int) { let temp = a a = b b = temp } var numb1 = 100 var numb2 = 200 print(“Before Swapping values are: (numb1) and (numb2)”) exchange(&numb1, &numb2) print(“After Swapping values are: (numb1) and (numb2)”) Output It will produce the following output − Before Swapping values are: 100 and 200 After Swapping values are: 200 and 100 Generic Functions Generic functions are special functions that can be used to access any data type like ”Int” or ‘String’ while maintaining the type safety. Or we can say that generic functions can work with different types without specifying the actual type at the time of declaration. Example In the following example, The function exchange() is used to swap values described in the above program and <T> is used as a type parameter. For the first time, function exchange() is called to return ”Int” values and the second call to the function exchange() will return ”String” values. Multiple parameter types can be included inside the angle brackets separated by commas. func exchange<T>(_ a: inout T, _ b: inout T) { let temp = a a = b b = temp } var numb1 = 100 var numb2 = 200 print(“Before Swapping Int values are: (numb1) and (numb2)”) exchange(&numb1, &numb2) print(“After Swapping Int values are: (numb1) and (numb2)”) var str1 = “Generics” var str2 = “Functions” print(“Before Swapping String values are: (str1) and (str2)”) exchange(&str1, &str2) print(“After Swapping String values are: (str1) and (str2)”) Output It will produce the following output − Before Swapping Int values are: 100 and 200 After Swapping Int values are: 200 and 100 Before Swapping String values are: Generics and Functions After Swapping String values are: Functions and Generics Type Parameters Type parameters are named as user-defined to know the purpose of the type parameter that it holds. Swift provides <T> as a generic type parameter name. However type parameters like Arrays and Dictionaries can also be named as key, values to identify that they belong to the type ‘Dictionary”. We are allowed to provide more than one type parameter by writing multiple type parameter names in the angle brackets, where each name is separated by a comma. Example // Generic Types struct TOS<T> { var items = [T]() mutating func push(item: T) { items.append(item) } mutating func pop() -> T? { return items.popLast() } } var tos = TOS<String>() tos.push(item: “Swift 4”) print(tos.items) tos.push(item: “Generics”) print(tos.items) tos.push(item: “Type Parameters”) print(tos.items) tos.push(item: “Naming Type Parameters”) print(tos.items) if let deletetos = tos.pop() { print(“Popped item: (deletetos)”) } else { print(“The stack is empty.”) } Output It will produce the following output − [“Swift 4”] [“Swift 4”, “Generics”] [“Swift 4”, “Generics”, “Type Parameters”] [“Swift 4”, “Generics”, “Type Parameters”, “Naming Type Parameters”] Popped item: Naming Type Parameters Generic Type and Extending a Generic Type In Swift, we are allowed to define generic types to create flexible and reusable structures, classes or enumerations that can easily work with any data type. Also, we are allowed to extend the functionality of generic types using the extension keyword. Example struct TOS<T> { var items = [T]() mutating func push(item: T) { items.append(item) } mutating func pop() -> T { return items.removeLast() } } var tos = TOS<String>() tos.push(item: “Swift 4”) print(tos.items) tos.push(item: “Generics”) print(tos.items) tos.push(item: “Type Parameters”) print(tos.items) tos.push(item: “Naming Type Parameters”) print(tos.items) extension TOS { var first: T? { return items.isEmpty ? nil : items[items.count – 1] } } if let first = tos.first { print(“The top item on the stack is (first).”) } Output It will produce the following output − [“Swift 4”] [“Swift 4”, “Generics”] [“Swift 4”, “Generics”, “Type Parameters”] [“Swift 4”, “Generics”, “Type Parameters”, “Naming Type Parameters”] The top item on the stack is Naming Type Parameters. Type Constraints Swift allows ”type constraints” to specify whether the type parameter inherits from a specific class, or to ensure protocol conformance standard. We are allowed to use them with classes and protocols to specify more complex requirements. While creating custom generic types we are allowed to create our own type constraints. Syntax Following is the syntax for the type constraints − Func functionName<T: className, U: protocolName>(variable1: T, variable2: U){ // Function body } Example // A generic function with a type constraint func show<T: CustomStringConvertible>(item: T) { print(item.description) } let str = “Welcome Swift” let number = 22 show(item: str) show(item: number) Output It will produce the following output − Welcome Swift 22 Where Clauses Type constraints enable the user to define requirements on the type parameters associated with a generic function or type. For defining requirements for associated types ”where” clauses are declared as part of the type parameter list. ”where” keyword is placed immediately after the list of type parameters followed by constraints of associated types, and equality relationships between types and associated types. Example protocol Container { typealias ItemType mutating func append(item: ItemType) var count: Int { get } subscript(i: Int) -> ItemType { get } }

Swift – Protocols

Swift – Protocols ”; Previous Next Protocols provide a blueprint for Methods, properties and other requirements functionality. It is just described as a methods or properties skeleton instead of an implementation. Methods and properties implementation can further be done by defining classes, functions and enumerations. Conformance of a protocol is defined as the methods or properties satisfying the requirements of the protocol. Defining Protocols in Swift In Swift, the definition of the protocol is quite similar to the class, structure or enumeration. A protocol is defined using the protocol keyword. Syntax Following is the syntax for the protocol − protocol SomeProtocol { // protocol definition } Protocols are declared after the class, structure or enumeration type names. Single and multiple protocol declarations are also possible. If multiple protocols are defined they have to be separated by commas. struct SomeStructure: Protocol1, Protocol2 { // structure definition } When a protocol has to be defined for a superclass, the protocol name should follow the superclass name with a comma. class SomeClass: SomeSuperclass, Protocol1, Protocol2 { // class definition } Property, Method and Initialization Requirements A protocol requires any conforming type which can provide property, method and initialization. Property Requirements − A protocol is used to specify a particular class type property or instance property. It only specifies the type or instance property rather than specifying whether it is a stored or computed property. Also, specify whether the property is ”gettable” or ”settable”. Property requirements are declared by ”var” keyword as property variables. {get set} is used to declare gettable and settable properties after their type declaration. Gettable is mentioned by {get} property after their type declaration. Syntax The following syntax is for defining properties in protocol − protocol SomeProtocol { var propertyName : Int {get set} } Method Requirements − A protocol is used to specify particular type methods or instance methods. It only contains the definition part without curly braces and body. It allows methods to have variadic parameters. Syntax The following syntax is for defining methods in protocol − protocol SomeProtocol { func methodName(parameters) } Mutating Method Requirements − If you want to specify a mutating method in the protocol then use the mutating keyword before the definition of the method. It allows structure and enumeration to adopt the protocol with the mutating method. Syntax The following syntax is for defining mutating methods in protocol − protocol SomeProtocol { mutating func methodName(parameters) } Initializer Requirements: A protocol is also used to specify an initializer that will implemented by conforming types. It only contains the definition part just like the normal initializers, but without and curly braces and a body. We can specify either designated or convenience initializers. Also, the class or structure that conforms to the protocol must use the required modifier before the implementation of the initializer. Protocol conformance is ensured on all subclasses for explicit or inherited implementation by ”required” modifier. When a subclass overrides its superclass initialization requirement it is specified by the ”override” modifier keyword. Syntax The following syntax is for defining initializers in protocol − protocol SomeProtocol { init(parameters) } Example Swift program to create a protocol that conforms by a class. // Protocol protocol classa { // Properties var marks: Int { get set } var result: Bool { get } // Method func attendance() -> String func markssecured() -> String } // Protocol protocol classb: classa { // Properties var present: Bool { get set } var subject: String { get set } var stname: String { get set } } // Class that conform Protocol class classc: classb { var marks = 96 let result = true var present = false var subject = “Swift 4 Protocols” var stname = “Protocols” func attendance() -> String { return “The (stname) has secured 99% attendance” } func markssecured() -> String { return “(stname) has scored (marks)” } } // Instance of class let studdet = classc() studdet.stname = “Swift 4″ studdet.marks = 98 // Accessing methods and properties print(studdet.markssecured()) print(studdet.marks) print(studdet.result) print(studdet.present) print(studdet.subject) print(studdet.stname) Output It will produce the following output − Swift 4 has scored 98 98 true false Swift 4 Protocols Swift 4 Example Swift program to create a protocol with mutating method requirements. // Protocol protocol daysofaweek { // Mutating method mutating func display() } // Enumeration that conforms to the Protocol enum days: daysofaweek { case sun, mon, tue, wed, thurs, fri, sat mutating func display() { switch self { case .sun: print(“Sunday”) case .mon: print(“Monday”) case .tue: print(“Tuesday”) case .wed: print(“Wednesday”) case .thurs: print(“Thursday”) case .fri: print(“Friday”) case .sat: print(“Saturday”) } } } // Instance of enumeration var res = days.wed res.display() Output It will produce the following output − Wednesday Example Swift program to create a protocol with an initializer that conforms to the class. // Protocol protocol tcpprotocol { // Initializer init(no1: Int) } class mainClass { var no1: Int // local storage init(no1: Int) { self.no1 = no1 // initialization } } // Class that conform protocol class subClass: mainClass, tcpprotocol { var no2: Int init(no1: Int, no2 : Int) { self.no2 = no2 super.init(no1:no1) } // Requires only one parameter for convenient method required override convenience init(no1: Int) { self.init(no1:no1, no2:0) } } // Class instances let obj1 = mainClass(no1: 20) let obj2 = subClass(no1: 30, no2: 50) print(“res is: (obj1.no1)”) print(“res is: (obj2.no1)”) print(“res is: (obj2.no2)”) Output It will produce the following output − res is: 20 res is: 30 res is: 50

Swift – Extensions

Swift – Extensions ”; Previous Next What are Extensions in Swift? Swift provides a special feature known as extension. Extensions are used to add new functionalities in the existing class, structure, enumeration or protocol type without overriding or modifying the existing code. This feature is useful when we want to extend the functionality of types that we cannot modify, such as third-party libraries, etc. Extensions are static additions to the type they are not dynamic. Also, they cannot add stored properties with default values. The following are the functionalities provided by the extensions − Adding computed properties and computed type properties Defining instance and type methods Providing new initializers Defining subscripts Defining and using new nested types Making an existing type conform to a protocol Defining Extensions in Swift Extensions are declared with the help of the extension keyword. Syntax Following is the syntax for the extension − extension SomeType { // Adding new functionality } Existing type can also be added with extensions to make it a protocol standard and its syntax is similar to that of classes or structures. extension SomeType: SomeProtocol, AnotherProtocol { // Describe protocol requirements } Extensions with Computed Properties Computed ”instance” and ”type” properties can also be extended with the help of extensions. Computed properties are those properties that do not store a value instead, they provide a getter and setter to retrieve and set other properties and values. Example Swift program to demonstrate how to add new functionality in the computed properties using the extension. // Adding new functionality to the computed property using an extension extension Int { var add: Int {return self + 100 } var sub: Int { return self – 10 } var mul: Int { return self * 10 } var div: Int { return self / 5 } } let addition = 3.add print(“Addition is (addition)”) let subtraction = 120.sub print(“Subtraction is (subtraction)”) let multiplication = 39.mul print(“Multiplication is (multiplication)”) let division = 55.div print(“Division is (division)”) let mix = 30.add + 34.sub print(“Mixed Type is (mix)”) Output It will produce the following output − Addition is 103 Subtraction is 110 Multiplication is 390 Division is 11 Mixed Type is 154 Extension with Initializers Swift provides the flexibility to add new initializers to an existing type using extensions. The user can add their own custom types to extend the types already defined and additional initialization options are also possible. Extensions support only init(). deinit() is not supported by the extensions. Example Swift program to demonstrate how to add new functionality in the initializer using the extension. struct sum { var num1 = 100, num2 = 200 } struct diff { var no1 = 200, no2 = 100 } struct mult { var a = sum() var b = diff() } let calc = mult() print (“Inside mult block (calc.a.num1, calc.a.num2)”) print(“Inside mult block (calc.b.no1, calc.b.no2)”) let memcalc = mult(a: sum(num1: 300, num2: 500),b: diff(no1: 300, no2: 100)) print(“Inside mult block (memcalc.a.num1, memcalc.a.num2)”) print(“Inside mult block (memcalc.b.no1, memcalc.b.no2)”) extension mult { init(x: sum, y: diff) { let X = x.num1 + x.num2 let Y = y.no1 + y.no2 } } let a = sum(num1: 100, num2: 200) print(“Inside Sum Block:( a.num1, a.num2)”) let b = diff(no1: 200, no2: 100) print(“Inside Diff Block: (b.no1, b.no2)”) Output It will produce the following output − Inside mult block (100, 200) Inside mult block (200, 100) Inside mult block (300, 500) Inside mult block (300, 100) Inside Sum Block:(100, 200) Inside Diff Block: (200, 100) Extension with Methods New instance methods and type methods can be added further to the subclass with the help of extensions. Example Swift program to demonstrate how to add new functionality in the methods using the extension. extension Int { func topics(summation: () -> ()) { for _ in 0..<self { summation() } } } 4.topics({ print(“Inside Extensions Block”) }) 3.topics({ print(“Inside Type Casting Block”) }) Output It will produce the following output − Inside Extensions Block Inside Extensions Block Inside Extensions Block Inside Extensions Block Inside Type Casting Block Inside Type Casting Block Inside Type Casting Block Extension with Mutating Instance Methods We can also add new functionality in the mutating instance methods of structure and enumeration using the extension. Example Swift program to demonstrate how to add new functionality in the mutating methods using the extension. extension Double { mutating func square() { let pi = 3.1415 self = pi * self * self } } var Trial1 = 3.3 Trial1.square() print(“Area of circle is: (Trial1)”) var Trial2 = 5.8 Trial2.square() print(“Area of circle is: (Trial2)”) var Trial3 = 120.3 Trial3.square() print(“Area of circle is: (Trial3)”) Output It will produce the following output − Area of circle is: 34.210935 Area of circle is: 105.68006 Area of circle is: 45464.070735 Extension with Subscripts Adding new subscripts to already declared instances can also be possible with extensions. Example Swift program to demonstrate how to add new functionality in the subscript using the extension. extension Int { subscript(var multtable: Int) -> Int { var no1 = 1 while multtable > 0 { no1 *= 10 –multtable } return (self / no1) % 10 } } print(12[0]) print(7869[1]) print(786543[2]) Output It will produce the following output − 2 6 5 Extension with Nested Types Nested types for class, structure and enumeration instances can also be extended with the help of extensions. Example

Swift – Methods

Swift – Methods ”; Previous Next Methods are the functions of a particular type, such as class, structure or enumeration. They define the behavior and functionality for instances of a type. They are generally accessed by the instances. Swift also supports type methods that are associated with the type itself. Instance Methods in Swift In Swift, instance methods are the functions that belong to the specific instance of a class, structure or enumeration. They are called on an instance of the type and can access and modify instance properties or other instance methods, or also add functionality related to the instance”s need. The syntax of the instance method is the same as the function. Instance method can also have, parameters, return type, parameter names, and argument labels. It can be written inside the {} curly braces. It has implicit access to methods and properties of the type instance. An instance method is called only using the instance of that particular type, we are not allowed to call an instance method without any instance. Syntax Following is the syntax of the instance method- func methodname(Parameters) -> returntype { Statement1 Statement2 — Statement N return parameters } Instance methods are accessed with ”.” dot syntax. instanceName.methodName() Example // Defining a class class Calculations { // Properties let a: Int let b: Int let res: Int // Initializer init(a: Int, b: Int) { self.a = a self.b = b res = a + b } // Instance method func tot(c: Int) -> Int { return res – c } // Instance method func result() { print(“Result is: (tot(c: 20))”) print(“Result is: (tot(c: 50))”) } } // Creating and initializing the instance of the class let pri = Calculations(a: 600, b: 300) // Accessing the instance method pri.result() Output It will produce the following output − Result is: 880 Result is: 850 Mutating Instance Method In Swift, structures and enumerations are value types, which means we cannot alter the properties inside the instance method. So to modify the properties inside a method we need to specify that method as a mutating method using the mutating keyword and the changes made by the method in its properties will written back to the original structure when the method ends. We can only mutate methods of structure and enumeration but not class because a class is a reference type so their properties can be modified without using mutating keyword. Also, we cannot call a mutating method on a constant of structure type. Syntax Following is the syntax of the mutating instance method − mutating func methodname(Parameters) -> returntype { Statement } Example Swift program to demonstrate the mutating method in structure. // Defining a structure struct CalculateSum { // Properties var num1 = 1 var num2 = 1 // Instance method func sum() -> Int { return num1 + num2 } // Mutating instance method mutating func increment(res: Int) { num1 *= res num2 *= res print(“New Number 1 is “, num1) print(“New Number 2 is “, num2) } } // Creating and initializing the instance of structure var obj = CalculateSum(num1: 10, num2: 12) // Calling mutating method obj.increment(res: 10) // Calling instance method print(“Sum is “, obj.sum()) Output It will produce the following output − New Number 1 is 100 New Number 2 is 120 Sum is 220 Assigning Instance to self within a Mutating Method In mutating methods, we are allowed to assign a new instance to the implicit self property. It will replace the existing instance with the new instance. While assigning a new instance to the self always be careful because it changes the state of the instance and any reference related to the original instance will not reflect the changes. Example Swift program to demonstrate how to assign an instance to self within a mutating method. // Defining a structure struct Student { var age: Int var name: String // Mutating method that assigns a new instance to self mutating func newValue() { self = Student(age: 23, name: “Jyoti”) } } // Creating an instance of the Student structure var obj = Student(age: 22, name: “Poonam”) // Calling the mutating method obj.newValue() // Displaying the updated values print(“New age: (obj.age), New name: (obj.name)”) Output It will produce the following output − New age: 23, New name: Jyoti Method Argument label and Parameter name in Swift Just like a function, a method can also have labels and names for its arguments and parameters. These labels and names provide a clear and descriptive context for the argument and parameter. The parameter name is used in the declaration of the method whereas the argument label is used when the method is called. By default, the argument label and parameter name are the same, but multiple parameters can have the same or unique argument label. The names of the parameters should be unique so that the compiler can easily distinguish them. We can also ignore the argument label by placing the underscore(_) before the name of the parameter. Syntax Following is the syntax for the argument label and parameter name − // Parameter name With argument label func methodname(argumentLabel parameterName: Type, parameterName: Type) -> returntype { Statement return value } methodname(name1:value, name2: value) // Parameter name without argument label func methodname(_name1: Type, _name2: Type) -> returntype { Statement return value } methodname(value1, value2) Example Swift program to demonstrate how to specify the parameter name and argument label in the method. // Defining class class CalculateSum { // Method with parameter name and argument label func addingTwoNumbers(num1 x:

Swift – Function vs Method

Swift – Function vs Method ”; Previous Next In Swift, functions and methods both are fundamental building blocks for optimizing and encapsulating code. It might be confusing to understand the difference between function and method, but we might think they are both the same. That”s not true. The methods are used in class, struct, and enum. They are called on the instances of that type and access and modify the properties of the instance. Whereas functions are defined independently or globally without creating a class or structure. Or we can say that a method is a function while a function is not a method. Swift Functions Functions are used to perform specific actions and are called by their names. It is very simple to pass the variables or constants as an argument while calling a function. Also, we can return a value from a function of any type. A function that works independently of a file can also be defined outside of it. Syntax Following is the syntax of a function − func functionName(parameters…) -> returnType { //Write statements here to perform actions } Example Swift program to demonstrate how to create and call a function. // Function without return value func show(msg: String) { print(“Welcome to, (msg)!”) } // Function call show(msg: “Tutorials Point”) // Function with return value func sumOfNumbers(_ nums: [Int]) -> Int { var sum = 0 // Calculating the sum of the numbers present in the array for n in nums { sum += n } return sum } // Function call with return value let inputNumbers = sumOfNumbers([3, 5, 6, 7, 1]) print(“Sum = (inputNumbers)”) Output It will produce the following output − Welcome to, Tutorials Point! Sum = 22 Swift Methods A method is a function and can be defined in classes, structures, and enumerations. Using methods, we can perform certain actions according to your requirements. As per our needs, we can define more than one method to perform different tasks. To access the defined methods in a class or structure we have to create an instance of the associated type. Using that object, we can call methods to perform tasks. Just like functions, we can also pass arguments while calling the method. Always remember that without creating an object of that class or struct we cannot access the methods. In the Swift language, there are two types of methods like the following − Instance Methods − As per their names, these are the instance-specific methods that can be called through the instances. The compiler will give us an error if we will try to access the methods without an instance of that class or struct. Also, we cannot call the methods of a class (for eg. Class Student) from another class”s instance. Type Methods − In Swift, we can define the type methods with prefix keywords like static or class. There is no need to create an instance of a class or struct to call type methods. They can be called directly from the type name. Syntax Following is the syntax of a method − func methodName(parameters…) -> returnType { //Write statements here to perform actions } Example Swift program to demonstrate how to create and call a method. // Defining a structure struct Student { // Properties let name: String let grade: Int // Instance method func displayInfo() { print(“name: (name)”) print(“grade: (grade)”) } // Type method static func dummyStudents() -> [Student] { return [Student(name: “Ray Sin”, grade: 4), Student(name: “Cherry Blossom”, grade: 2), Student(name: “Perry Scope”, grade: 7)] } } // Creating instance of the structure let anne = Student(name: “Anne Teak”, grade: 5) // Calling instance method from object anne anne.displayInfo() // Calling type method let students = Student.dummyStudents() print(“number of students: “, students.count) Output It will produce the following output − name: Anne Teak grade: 5 number of students: 3 Visual Identification Between Function and Method The Swift language shows how a function and method are denoted. It is visible that both are denoted as follows − The function has an icon like ƒ. The method has an icon of M. Difference Between Methods and Functions in Swift The following table will show the major difference between the methods and functions in Swift − Function Method The function is defined as independent. So that, we can define functions outside of the class. They are connected with a class or struct itself. Outside the scope, you can not define the methods. Functions are independent properties of structured languages like C/C++. Methods works within the scope of an object similar to Object-oriented languages like C#, Java, Swift, etc. Functions don”t capture any reference variables or constants. Methods are called using reference variables (or instances) only. While functions do not belong to classes, they perform individually. Methods are defined to manipulate the particular instance of that class or struct. No need to create objects to call them. An object is required to access them. Simply, every function is not a method. While every method is a function. Print Page Previous Next Advertisements ”;

Swift – Concurrency

Swift – Concurrency ”; Previous Next Concurrency provides the ability for Swift program to execute multiple tasks or operations simultaneously. Or we can say that it allows us to write asynchronous and parallel codes in a structured way. We are allowed to suspend and resume asynchronous code. Concurrency will improve the responsiveness and performance of the application. Asynchronous Functions In Swift, asynchronous functions or methods are the special type of functions or methods that can perform non-blocking and asynchronous operations. Such types of functions can be suspended in between their execution or they can also pause to wait for something. Also, we are allowed to mark the places where we want to suspend the execution of the function. To create a synchronous function or method we have to use the async keyword in the declaration part after the parameter list and before the return arrow. Syntax Following is the syntax for asynchronous function − func functionName(parameter) async -> returnType{ // statement } To suspend the execution of the asynchronous function or method until the awaited asynchronous operation completes, we have to use the await keyword in front of the call. It makes concurrent code easier to read. Following is the syntax for suspending the execution of asynchronous functions − await functionName(parameter) Asynchronous function or method can also throw an error and we can handle that error with the help of try and catch block. Following is the syntax for handling errors by asynchronous functions − func functionName() async throws -> Data { // asynchronous code that may throw an error } do { let data = try await functionName() // process data } catch { // handle error } We can also call asynchronous functions in parallel by using the async keyword in front of let while defining a constant and then writing the await keyword whenever we use the constant. Following is the syntax for calling asynchronous functions in parallel − // Calling asynchronous function in parallel async let result1 = functionName1(parameter) async let result2 = functionName2(parameter) // Suspend execution let suspendExecution = await[result1, result2] Example Swift program for asynchronous function. // Asynchronous function func randomFunc() async -> Int { Int.random(in: 10…40) } let result = await randomFunc() print(“Random Number:”, result) Output It will produce the following output − Random Number: 13 Task and Task Group In Swift, task and task groups are the main concepts that help us to work with asynchronous code in a structured manner. A task is a unit of work that can be executed concurrently. All the asynchronous codes that execute are part of the task. Generally, a task can perform one operation at a time but when we create multiple tasks then Swift will schedule them to run simultaneously. Whereas a task group is used to manage a collection of tasks and collectively perform operations on them. Here the tasks are arranged in a hierarchy, which means each task in the given group has the parent task and child tasks and this relationship is important because − While working with a parent task, you cannot forget to wait for its task to complete. If you set the priority of the child task to high then the priority of the parent task will automatically be set to high. If the parent task gets cancelled, then the child task will also cancelled. The local values of tasks can easily propagate to child tasks Task Cancellation We are allowed to cancel the execution of the task. Or we can terminate the ongoing task before it is completed. It is helpful in various cases like cleaning up resources and stopping long running operations. We can cancel the task with the help of the cancel() method provided by Swift. Example Swift program to create and cancel a task. import Foundation class MyTaskManager { private var task: DispatchWorkItem? func createTask() { // Create a DispatchWorkItem task = DispatchWorkItem { for i in 1…5 { if self.task?.isCancelled ?? false { print(“Task cancelled”) return } print(“Running task – (i)”) } print(“Task completed successfully”) } // Execute the task on a background queue DispatchQueue.global().async(execute: task!) } func cancelTask() { // Cancelling the task task?.cancel() } } let obj = MyTaskManager() // Create and run the task obj.createTask() // Wait for a while sleep(2) // Cancel the task obj.cancelTask() Output It will produce the following output − Running task – 1 Running task – 2 Running task – 3 Running task – 4 Running task – 5 Task completed successfully Actor As we know tasks are used to break our programs into isolated or concurrent pieces, which makes them run safely at the same time. And to add some information between these tasks Swift provides Actors. Actors are reference types and it allows only one task to access its mutable state at a time. That makes code run safely in multiple tasks and can easily interact with the same instance of an actor. In actor, if outside code tries to access the properties directly, then we will get an error. We can declare an actor with the help of the actor keyword. Also, we are allowed to create instances of actor just like class and structure to access the properties and methods of the actor. To suspend the execution of the actor we can use the await keyword. Syntax Following is the syntax for calling asynchronous functions in parallel − // Calling asynchronous function in parallel async let result1 = functionName1(parameter) async let result2 = functionName2(parameter) // Suspend execution let suspendExecution = await[result1, result2] Example