Swift – Quick Guide

Swift – Quick Guide ”; Previous Next Swift – Overview Swift 4 is a new programming language developed by Apple Inc for iOS and OS X development. Swift 4 adopts the best of C and Objective-C, without the constraints of C compatibility. Swift 4 makes use of safe programming patterns. Swift 4 provides modern programming features. Swift 4 provides Objective-C like syntax. Swift 4 is a fantastic way to write iOS and OS X apps. Swift 4 provides seamless access to existing Cocoa frameworks. Swift 4 unifies the procedural and object-oriented portions of the language. Swift 4 does not need a separate library import to support functionalities like input/output or string handling. Swift 4 uses the same runtime as the existing Obj-C system on Mac OS and iOS, which enables Swift 4 programs to run on many existing iOS 6 and OS X 10.8 platforms. Swift 4 comes with playground feature where Swift 4 programmers can write their code and execute it to see the results immediately. The first public release of Swift was released in 2010. It took Chris Lattner almost 14 years to come up with the first official version, and later, it was supported by many other contributors. Swift 4 has been included in Xcode 6 beta. Swift designers took ideas from various other popular languages such as Objective-C, Rust, Haskell, Ruby, Python, C#, and CLU. Swift – Environment Local Environment Setup Swift 4 provides a Playground platform for learning purpose and we are going to setup the same. You need xCode software to start your Swift 4 coding in Playground. Once you are comfortable with the concepts of Swift 4, you can use xCode IDE for iOS/OS x application development. To start with, we consider you already have an account at Apple Developer website. Once you are logged in, go to the following link − Download for Apple Developers This will list down a number of software available as follows − Now select xCode and download it by clicking on the given link near to disc image. After downloading the dmg file, you can install it by simply double-clicking on it and following the given instructions. Finally, follow the given instructions and drop xCode icon into the Application folder. Now you have xCode installed on your machine. Next, open Xcode from the Application folder and proceed after accepting the terms and conditions. If everything is fine, you will get the following screen − Select Get started with a playground option and enter a name for playground and select iOS as platform. Finally, you will get the Playground window as follows − Following is the code taken from the default Swift 4 Playground Window. import UIKit var str = “Hello, playground” If you create the same program for OS X program, then it will include import Cocoa and the program will look like as follows − import Cocoa var str = “Hello, playground” When the above program gets loaded, it should display the following result in Playground result area (Right Hand Side). Hello, playground Congratulations, you have your Swift 4 programming environment ready and you can proceed with your learning vehicle “Tutorials Point”. Swift – Basic Syntax We have already seen a piece of Swift 4 program while setting up the environment. Let”s start once again with the following Hello, World! program created for OS X playground, which includes import Cocoa as shown below − /* My first program in Swift 4 */ var myString = “Hello, World!” print(myString) If you create the same program for iOS playground, then it will include import UIKit and the program will look as follows − import UIKit var myString = “Hello, World!” print(myString) When we run the above program using an appropriate playground, we will get the following result − Hello, World! Let us now see the basic structure of a Swift 4 program, so that it will be easy for you to understand the basic building blocks of the Swift 4 programming language. Import in Swift 4 You can use the import statement to import any Objective-C framework (or C library) directly into your Swift 4 program. For example, the above import cocoa statement makes all Cocoa libraries, APIs, and runtimes that form the development layer for all of OS X, available in Swift 4. Cocoa is implemented in Objective-C, which is a superset of C, so it is easy to mix C and even C++ into your Swift 4 applications. Tokens in Swift 4 A Swift 4 program consists of various tokens and a token is either a keyword, an identifier, a constant, a string literal, or a symbol. For example, the following Swift 4 statement consists of three tokens − print(“test!”) The individual tokens are: print(“test!”) Comments Comments are like helping texts in your Swift 4 program. They are ignored by the compiler. Multi-line comments start with /* and terminate with the characters */ as shown below − /* My first program in Swift 4 */ Multi-line comments can be nested in Swift 4. Following is a valid comment in Swift 4 − /* My first program in Swift 4 is Hello, World! /* Where as second program is Hello, Swift 4! */ */ Single-line comments are written using // at the beginning of the comment. // My first program in Swift 4 Semicolons Swift 4 does not require you to type a semicolon (;) after each statement in your code, though it’s optional; and if you use a semicolon, then the compiler does not complain about it. However, if you are using multiple statements in the same line, then it is required to use a semicolon as a delimiter, otherwise the compiler will raise a syntax error. You can write the above Hello, World! program as follows − /* My first program in Swift 4 */ var myString = “Hello, World!”; print(myString) Identifiers A Swift 4 identifier is a name used to identify a variable, function, or any other userdefined item. An

Swift – Compile Online

Compile Swift Online ”; Previous Next You really do not need to set up your own environment to start learning Swift programming. Reason is very simple, we already have set up Swift environment online, so that you can execute all the available examples online at the same time when you are doing your theory work. This gives you confidence in what you are reading and to check the result with different options. Feel free to modify any example and execute it online. Try following example using Live Demo option available at the top right corner of the below sample code box: Live Demo let constA = 42 print(constA) let constB:Float = 3.14159 print(constB) For most of the examples given in this tutorial, you will find Live Demo option, so just make use of it and enjoy your learning. Print Page Previous Next Advertisements ”;

Swift – Access Control

Swift – Access Control ”; Previous Next Access controls are used to restrict access to the specified part of the code or module. It prevents unauthorized access and implements encapsulation. The access control mechanism controls the access of the methods and properties of classes, structures and enumerations. Constants, variables and functions in a protocol are restricted and allowed access as global and local through access control. Access control applied to properties, types and functions can be referred to as ”entities”. The access control model is based on modules and source files. The module is defined as a single code distribution unit and can be imported using the keyword ”import”. A source file is defined as a single source code file within a module to access multiple types and functions. Access Levels in Swift Swift supports the following access levels and they are: Access Levels Definition Open It is the least restrictive access level. It is applicable only to classes and class memebers. It allows class and class members to be subclassed or overrridden in another module. Public It allows entities to be access from any source file within the same or different module. Internal It allows entities to be used within any source file from their defining module, but not outside of that module. Private It restricts the use of an entity to its own defining source file. It hides the implementation details of a specific code functionality. It is the most restrctive access level. File-Private It also restricts the use of an entity to its own defining source file. It hides the implementation details of a specific code functionality when those details are used inside the entire file. Rules of using Access levels Following are some rules that must be known by the developers while using access level − The public variable can not be defined as internal, file-private or private. The function does not have a higher access level than its parameter and return type. The default access level for all the entities is internal. The default access level for single-target apps is internal. The default access level for frameworks is either open or public. Syntax public class SomePublicClass {} internal class SomeInternalClass {} private class SomePrivateClass {} public var somePublicVariable = 0 internal let someInternalConstant = 0 private func somePrivateFunction() {} Access Control for Function types Some functions may have arguments declared inside the function without any return values. The following program declares a and b as arguments to the sum() function. Inside the function itself, the values for arguments a and b are passed by invoking the function call sum() and its values are printed thereby eliminating return values. To make the function”s return type as private, declare the function”s overall access level with the private modifier. Example Swift program to demonstrate access control for function types. // Private function private func sum(a: Int, b: Int) { let a = a + b let b = a – b print(a, b) } // Calling the function sum(a: 20, b: 10) sum(a: 40, b: 10) sum(a: 24, b: 6) Output It will produce the following output − 30 20 50 40 30 24 Access Control for Enumeration types The enumeration in Swift automatically receives the same access level for individual cases of an enumeration. Consider for example accessing the student name and marks secured in three subjects enumeration name is declared as a student and the members present in the enum class are a name that belongs to string datatype, marks are represented as mark1, mark2 and mark3 of datatype Integer. To access either the student name or marks they have scored. Now, the switch case will print the student”s name if that case block is executed otherwise it will print the marks secured by the student. Example Swift program to demonstrate access control for enumeration types. // Enumeration public enum Student { case Name(String) case Mark(Int, Int, Int) } var studDetails = Student.Name(“Swift”) var studMarks = Student.Mark(98, 97, 95) switch studDetails { case .Name(let studName): print(“Student name is: (studName).”) case .Mark(let Mark1, let Mark2, let Mark3): print(“Student Marks are: (Mark1), (Mark2), (Mark3).”) } Output It will produce the following output − Student name is: Swift. Access Control for SubClasses Swift allows the user to subclass any class that can be accessed in the current access context. A subclass cannot have a higher access level than its superclass. The user is restricted from writing a public subclass of an internal superclass. Example Swift program to demonstrate access control for subclasses. // Class public class Cricket { internal func display() { print(“Welcome to Swift Super Class”) } } // Subclass internal class Tennis: Cricket { override internal func display() { print(“Welcome to Swift Sub Class”) } } let cricketInstance = Cricket() cricketInstance.display() let tennisInstance = Tennis() tennisInstance.display() Output It will produce the following output − Welcome to Swift Super Class Welcome to Swift Sub Class Access Control for Constants, variables, properties and subscripts We are allowed to control the visibility of the constants, variables, properties and subscripts with the help of access controls. When a constant, variable, property or subscript uses private type, then that constant, variable, property, or subscript must be marked as private. And we are not valid to write a public property with a private type. Similarly, a subscript cannot be more public than its return type. Example private var privateInstance = SomePrivateClass() Access Control for Getters and

Swift – Error handling

Swift – Error Handling ”; Previous Next Error handling is a process of managing and responding to unexpected situations that occur during the execution of the program. Errors may occur due to various reasons like hardware issues, logical mistakes, unexpected user input, etc. Swift provides good support for catching, throwing, and manipulating recoverable errors during runtime. The main goals of error handling are: Detect Errors − Identify where and what type of error occurs in the program. Reporting Errors − Report the details of the error to the developer or end-user. Handling Errors − Take proper action against the occurred error which may include providing an error message, logging information for debugging or implementing strategies for recovery. Now in this article, we will discuss how errors are represented, propogated, and handled by the Swift. How an error is represented in Swift? In Swift, an error is represented by using the type that conforms to the Error protocol. The Error protocol is empty, which means it does not have any specific methods and properties to implement instead it allows us to create our own custom error types by defining a new type that conforms to the Error protocol. The best way to represent errors is enumeration. It grouped all the related error conditions with associated values and information about the error’s behaviour. Example The following Swift example will show how to represent an error. enum MyNewError: Error { case invalidInput case fileNotFound case networkError // Add more cases if you require } Throwing Error in Swift In Swift, throwing an error means when a function or a method detects something unexpected that prevents it from executing in the normal way, then it throws an error that tells that something unexpected has occurred. It is further helpful in handling the error. We can throw errors with the help of a throw statement. Syntax Following is the syntax for throwing an error − throw enumerationName.error Example Following Swift”s example we show how to throw an error. throw MyNewError.fileNotFound Propagating Errors Using Throwing Functions We can propagate errors from the throwing function. The throwing function is a function marked with the throw keyword. In Swift, functions, methods, or initializers can throw errors. When a function, method, or initializer encounters an error, then they can use the throws keyword in their declaration part after the parameter and before the return arrow(->). Only the throwing function is allowed to propagate errors. If an error occurs inside the non-throwing function, then that error must be handled inside that function. Syntax Following is the syntax for the throwing function − func functionName(parameterList) throws -> ReturnType Example The following Swift program will show how to throw an error using the throwing function. enum MyNewError: Error { case invalidInput case fileNotFound case networkError } // Throwing Function func processData(_ enterValue: String) throws { guard !enterValue.isEmpty else { throw MyNewError.invalidInput } } // Handling errors do { // Calling throwing function try processData(“”) print(“Successful”) } catch MyNewError.invalidInput { print(“Invalid input”) } catch { print(“Unexpected error occurred: (error)”) } Output It will produce the following output − Invalid input Disabling Error Propagation We can disable error propagation with the help of try! Keyword. It is helpful when we are confident the error does not occur at runtime and can simplify the error handling code. However, be careful while using try! Keyword if an error occurs, then our program will crash at runtime. Example Swift program to demonstrate how to disable error propagation. // Set of errors enum myNewError: Error { case divisionByZero case invalidInput } // Throwing function func divideNum(_ dividend: Int, by divisor: Int) throws -> Int { guard divisor != 0 else { throw myNewError.divisionByZero } return dividend / divisor } // Here we”re sure that the divisor is not zero, // so we use try! to disable error propagation. let output = try! divideNum(10, by: 2) print(output) Output It will produce the following output − 5 Handling Errors Using Do-Catch In Swift, we can handle errors with the help of a do-catch statement. It makes our code more robust and allows us to provide specific error-handling logic for various errors. In the do-catch statement, the do block contains the code that might throw an error and the catch block handles the specific error that occurs in the do block. Not all the errors thrown by the do clause are handled by the catch clause. If none of the catch clauses handle the occurred error, then that error will propagate to the surrounding scope and the surrounding scope will handle the propagated error. If the error propagated to the top-level scope without handling then we will get a runtime error. In the non-throwing functions, the errors are handled by the enclosed do-catch statement whereas in throwing functions the errors are handled by the enclosed do-catch statement or the caller. Syntax Following is the syntax of the do-catch statement − do { try<expression> } catch <pattern1>{ // statement } catch <pattern2>{ // statement } catch <pattern3>, <pattern4> where <condition>{ // statement } catch { //statement // catch clause without pattern can match any error } Example Swift program to demonstrate how to handle errors using do-catch blocks. // Set of errors enum myNewError: Error { case divisionByZero case invalidInput } // Throwing function func divideNum(_ dividend: Int, by divisor: Int) throws -> Int { guard divisor != 0 else { throw myNewError.divisionByZero } return dividend / divisor } // Handling error using do-catch statement do { let result = try divideNum(10, by:

Swift – Singleton class

Swift – Singleton Class ”; Previous Next A Singleton Class is a special class which have only one object and will make sure that your application or program uses that object. If you try to create another variable of singleton class you will get an error. Singleton class is easy to use but it has a major drawback which is global access, which means you can access singleton class globally by sharing the instance of the class. Which makes it hard to maintain, can lead to concurrency issues, etc. So to avoid excess use of singleton object we use dependency injection. Dependency injection passes the singleton object to the object where it is required. If a class depends upon the singleton and they are present in different contexts, then you have to import a singleton into that context without importing the class cannot access the singleton. Syntax Following is the syntax of the Singleton Class − class Name{ // body } Creating and Accessing Singleton Class We can create a singleton class just like the normal class using the “class” keyword but with some different rules and they are − A singleton class should have a private initializer. A singleton class should have a static-type object. Private Initializer This private initializer prevents the object creation from outside the class. If you try to create an object outside the class you will get an error. To create a private initializer we will use a “private” keyword. Syntax Following is the syntax for private initializer − private init(){} Example Swift program to create a singleton class with a private initializer. import Foundation // Outer class class SingletonClass{ // Creating a private initializer private init(){} func show(){ print(“Hello”) } } // Creating object outside the class // We will get an error let myObject = SingletonClass() myObject.show() Output It will produce the following output − main.swift:16:16: error: ”SingletonClass” initializer is inaccessible due to ”private” protection level let myObject = SingletonClass() Here the private protection level prevents us from creating an object outside the class. So to overcome this error we have to create an object inside the class. Static Object If we have a static object inside the single class we can easily access the object by using the class name. To create a static object we use the “Static” keyword. Syntax Following is the syntax for static objects − static let objectName = className() Following is the syntax for accessing static objects − let variableName = className.objectName Example Swift program to create a singleton class with an object. import Foundation // Singleton class class SingletonClass{ // Creating object outside the class static let myObject = SingletonClass() // Creating a private initializer private init(){} // Method func show(){ print(“Hello I am Singleton Class”) } } // Accessing the object let ob = SingletonClass.myObject // Accessing the method ob.show() Output It will produce the following output − Hello I am Singleton Class Singleton Class Normal Class It have only one instance throughout the lifetime of the program. It can have multiple instances. It does not allows you to create instances of the class. It allows you to directly create instances of the class using its initializer. You can access the instance with the help of shared properties and methods that provide global access to the object. You can directly access the instances. It is less flexible in terms of creating objects and can use tight coupling between different parts of the code. It is more flexible in terms of creating objects and can allow loose coupling between different parts of the code. Testing singleton class is difficult because of global state and dependencies. Testing normal classes is much more easier. Print Page Previous Next Advertisements ”;

Swift Random Numbers

Swift – Random Numbers ”; Previous Next Random Numbers are the sequence of numbers that are generated by the system without any pre-defined pattern or in an unpredictable manner. They are commonly used in chance events, produce unpredictable outcomes, etc. Random numbers are widely used in cryptography, gaming, statistical analysis, generating unique id/sessions for users, etc. In Swift, we can find random numbers using the following methods − random(in:) function random(in: using:) function randomElement() function Using random(in:) Function We can find random numbers with the help of the random(in:) function. This function returns a random number from the given range. Using this function, we can generate random numbers of Int, Double, Float and Bool types. Syntax Following is the syntax of the random(in:) function − static func random(in: inputRange) Here this function takes only one parameter which is the inputRange. The inputRange represents a range in which a random() function creates a random number. Return Value This function returns a random number from the given range. Example Swift program to generate random numbers using random(in:) function. import Foundation // Generating a random number of Int type var randomNumber1 = Int.random(in: 10…23) print(“Random Number:”, randomNumber1) // Generating a random number of Float type var randomNumber2 = Float.random(in: 10.2…23.2) print(“Random Number:”, randomNumber2) // Generating a random number of Double type var randomNumber3 = Double.random(in: 15.2..<25.2) print(“Random Number:”, randomNumber3) // Generating a random number of Bool type var randomNumber4 = Bool.random() print(“Random Number:”, randomNumber4) Output It will produce the following output − Random Number: 20 Random Number: 14.4035845 Random Number: 17.450544998301993 Random Number: true Using random(in:using:) Function To generate random numbers Swift supports a pre-defined function named random(in:using:) function. This function generates a random number within the given range with the help of a given generator. It also generates random numbers of Int, Double, Float and Bool types. Syntax Following is the syntax of the random(in:using:) function − static func random(in: inputRange, using: generator) This function takes two parameters − inputRange − It represents a range. Its value must not be empty. generator − It represents the generator using which random(in:using:) function will generate a random number. Return Value This function returns a random number within the specified range. Example Swift program to generate random numbers using random(in:using:) function. import Foundation // Specifying a generator var myGenerator = SystemRandomNumberGenerator() // Generating a random number of Int type var randomNumber1 = Int.random(in: 30…43, using: &myGenerator) print(“Random Number:”, randomNumber1) // Generating a random number of Float type var randomNumber2 = Float.random(in: 12.2…33.2, using: &myGenerator) print(“Random Number:”, randomNumber2) // Generating a random number of Double type var randomNumber3 = Double.random(in: 35.2..<45.2, using: &myGenerator) print(“Random Number:”, randomNumber3) // Generating a random number of Bool type var randomNumber4 = Bool.random(using: &myGenerator) print(“Random Number:”, randomNumber4) Output It will produce the following output − Random Number: 34 Random Number: 20.267605 Random Number: 42.47363754282583 Random Number: false Using randomElement() Function When we are working with collections such as an array and dictionary, we can use the randomElement() function. This function returns a random element from the given collection. The value returned by this function is an optional type so we must unwrap it using (!). Syntax Following is the syntax of the randomElement() function − static func randomElement() Return Value This function returns a random number from the specified collection. If the collection is empty, then it will return nil. Example Swift program to generate a random element from the given collection. import Foundation let myVeggies = [“Lemon”, “Cabbage”, “Green Chilly”, “Potato”] // Getting random element let randomVeggie = myVeggies.randomElement()! print(“Random Element: (randomVeggie)”) Output It will produce the following output − Random Element: Lemon Print Page Previous Next Advertisements ”;

Swift – Discussion

Discuss Swift ”; Previous Next Swift 4 is a new programming language developed by Apple Inc for iOS and OS X development. Swift 4 adopts the best of C and Objective-C, without the constraints of C compatibility. Swift 4 uses the same runtime as the existing Obj-C system on Mac OS and iOS, which enables Swift 4 programs to run on many existing iOS 6 and OS X 10.8 platforms. Print Page Previous Next Advertisements ”;

Swift – SwiftyJSON

Swift – SwiftyJSON ”; Previous Next What is JSON Data? JSON is known as JavaScript Object Notation. It is a lightweight and most commonly used data interchange format that is easy to read and write. It is generally used to transmit data between a server and an application. JSON data is generally represented in key-value pairs. For example − { “name”: “Monika”, “age”: 23, “city”: “Delhi” } Here name, age and city are the keys and Monika, 23 and Delhi are their respective values. In Swift, we can work with JSON data using the SwiftyJSON library. SwiftyJSON SwiftyJSON is a very important and powerful Swift library to handle JSON data in Swift programming language. It is commonly used to read and process JSON data returned by the APIs. It simplifies the process of parsing and working with JSON data in Swift easily by providing subscript syntax. It also provides various data types. Before SwiftyJSON the developer faced various problems while working with JSON data in Swift and the problems were − Verbose Syntax − Before the SwiftyJSON library the JSON data in Swift was handled by the JSONSerialization class which provides verbose syntaxes. Developers had to work with nested casting and a significant amount of optional unwrapping which makes code more complex and hard to read. Type Safety − While handling JSON data Swift doesn”t provide any direct way to handle optional values or nested structures in a type-safe manner. The user has to either use conditional casting or manually check the presence of keys. Readability − Reading and extracting values from the JSON was less readable. Swift doesn”t provide easy and clean syntax to work with JSON data. Error-handling − The developer had to use the do-catch block to handle errors manually because Swift does not provide any straightforward method to handle errors for JSON parsing and extracting. Lack of Convenience − Before SwiftyJSON developers had to write more boilerplate code to pars JSON data which makes the parsing more time-consuming. These issues are later solved by the SwiftJSON library. It provides more expressive and straightforward methods to deal with JSON data in Swift. How to use SwiftyJSON? To use the SwiftyJSON library in your project you have to follow the following steps − Step 1 − Install SwiftyJSON. To install SwiftyJSON you can use either CocoaPods or Swift Package Manager. Here we will use Swift Package Manager. So Open Xcode project → go to File → Swift Packages → Add Package Dependency and then enter the following SwiftyJSON GitHub repository URL − https://github.com/SwiftyJSON/SwiftyJSON.git Now follow the prompts to add the package. Step 2 − Now to use SwiftyJSON import the library at the top of the code using the import keyword. import SwiftyJSON Creating JSON Object: To create a JSON object SwiftyJSON provides the following initialiser. let object = JSON(data: dataObject) Or let obj = JSON(jsonObj) Accessing data − You can use subscripts to access JSON data. // Getting string from JSON dictionary let stdName = json[“name”].stringValue // Getting int from JSON array let value = json[1].int= Iterating over an array or dictionary − SwiftyJSON supports a for-in loop to iterate over the elements of an array or dictionary. // For array for(index, element):(String, JSON) in json{ Write something } // For dictionary for(key, element):(String, JSON) in json{ Write something } Example import SwiftyJSON // JSON string let inputJsonString = “”” { “name”: “Mohan”, “age”: 40, “branch”: “CSE” }””” if let jsonObj = inputJsonString.data(using: .utf8) { let x = try? JSON(data: jsonObj) // Accessing values using SwiftyJSON subscript syntax let name = x?[“name”].stringValue let age = x?[“age”].intValue let branch = x?[“branch”].stringValue // Perform operations print(“Name: (name ?? “N/A”)”) print(“Age: (age ?? 0)”) print(“Branch: (branch ?? “N/A”)”) } Output This code will work on Xcode. It will not work on an online Swift compiler. − Name: Mohan Age: 40 Branch: CSE Print Page Previous Next Advertisements ”;

Swift – for in loop

Swift – for-in Loop ”; Previous Next Swift for-in Loop The for-in loop iterates over collections of elements, such as ranges arrays, sets, dictionaries, etc. It iterates through each element of the specified collection without any explicit index manipulation. It is the most commonly used control flow statement because it expresses logic in a very clean and readable way. It is also compatible with functional programming, which means you can easily use high-order functions like filter(), map(), reduce, etc with a for-in loop. Syntax Following is the syntax of the for-in loop − for index in var{ Statement(s) } Flow Diagram The following flow diagram will show how the for-in loop works − Example Swift program to demonstrate the use of for-in loop. import Foundation var someInts:[Int] = [10, 20, 30] for index in someInts { print( “Value of index is (index)”) } Output It will produce the following output − Value of index is 10 Value of index is 20 Value of index is 30 Swift for-in Loop with Underscore “_” In a for-in loop, we can also ignore values from the given collection with the help of underscore “_”. Here we use underscore “_” in place of variable Name in the for-in loop. It will ignore the current value while iterating. It is commonly used when we only want to iterate a given number of times and does not require the value from the collection. Syntax Following is the syntax of the for-in loop with underscore − for _ in var{ Statement(s) } Example Swift program to demonstrate how to use for-in loop with underscore. import Foundation let numbers = [3, 5, 76, 12, 4] // Using the underscore to ignore the values for _ in numbers { // Following code will execute in each iteration print(“Hello!! for-in loop!”) } Output It will produce the following output − Hello!! for-in loop! Hello!! for-in loop! Hello!! for-in loop! Hello!! for-in loop! Hello!! for-in loop! Swift for-in Loop with Ranges We can also use range with a for-in loop. A range is the easiest way to represent a range of values in the for-in loop, it can be open, closed or half-open. The for-in loop iterates over each value in the given range and in each iteration, the loop variable takes the value of the current element in the range. Syntax Following is the syntax of the for-in loop with range − // With a closed range for variableName in start…end{ Statement(s) } // With half-open range for variableName in start..<end{ Statement(s) } Example Swift program to demonstrate how to use for-in loop with range. import Foundation // Using closed Range print(“Loop 1:”) for x in 1…6 { print(x) } // Using half-open Range print(“Loop 2:”) for y in 1..<6 { print(y) } Output It will produce the following output − Loop 1: 1 2 3 4 5 6 Loop 2: 1 2 3 4 5 Swift for-in Loop with stride() Function We can use the stride() function with a for-in loop. The stride() function iterates over a range of values with a specific step between them. It is generally used to achieve more complex iteration patterns or can create a loop with a customized iteration pattern. Syntax Following is the syntax of the for-in loop with stride() function − for variableName in stride(from: value, to: value, by: value){ statement(s) } Parameters The stride() function takes three parameters − from − It contains the starting value of the range. to − It contains the end value of the range. Its value does not include. by − It contains the number of steps or strides between the values. If its value is positive, then the stride iterates in an upward direction or if the value is negative, then the stride iterates in the downward direction. Example Swift program to demonstrate how to use for-in loop with stride() function. import Foundation // The stride() function moves in upward direction print(“Loop 1:”) for x in stride(from: 1, to: 7, by: 2) { print(x) } // The stride() function moves in downward direction print(“nLoop 2:”) for y in stride(from: 7, to: 1, by: -2) { print(y) } Output It will produce the following output − Loop 1: 1 3 5 Loop 2: 7 5 3 Swift for-in Loop with where Clause Swift also provides a where clause which we can use with a for-in loop. A where clause is used to filter out only those elements that satisfy the condition specified in the where clause from the given collection. It can work with all iterable collections such as arrays, sets, and dictionaries. Syntax Following is the syntax of the for-in loop with where clause − for variableName in collectionName where condition{ Statement(s) } Example Swift program to demonstrate how to use for-in loop with where clause. import Foundation let nums = [43, 23, 66, 12, 2, 45, 33] // Using the where clause to filter out only even elements from the array for n in nums where n % 2 == 0 { print(“Even number is (n)”) } Output It will produce the following output − Even number is 66 Even number is 12 Even number is 2 Print Page Previous Next Advertisements ”;

Swift Opaque and Boxed Type

Swift – Opaque & Boxed Type ”; Previous Next Sometimes developers want to hide the details about the type. So Swift provides two special mechanisms named Opaque Types and Boxed Types. Using these two mechanisms we can manage and abstract the underlying details of types. The opaque type is used to hide the concrete type behind the protocols whereas the boxed type is used to wrap values in a container. Opaque Type The opaque type allows us to work with values of a specific type without showing the underlying concrete type. Or we can say that the opaque type is used to hide its return value type. It describes the return value in terms of the protocol it supports rather than showing the concrete type of the function’s return type. It preserves the type identity, which means the Swift compiler can access the type information but the user of the module cannot. It enhances the abstraction, encapsulation and modularity of the code by hiding the return type of the function or method and showing only the conforms to a certain protocol or structure. In Swift, we are allowed to use opaque return types with generics. Also if a function with opaque type is returned from multiple locations, then all the values returned by that function must have the same type. We can define opaque type using the some keyword along with the protocol or type. Syntax protocol ProtocolName { func methodName() -> String } func functionNAme() -> some ProtocolName { // Implementation that returns a type conforming to the given protocol} Example Swift program to demonstrate opaque type. // Function with return opaque type func randomElement() -> some Equatable{ Int.random(in: 0…14) } let elementOne = randomElement() let elementTwo = randomElement() // Now comparing the first and second elements returned by the function print(elementOne == elementTwo) Output It will produce the following output − false Example Swift program to demonstrate opaque type. // Define a protocol for shapes protocol Shape { func area() -> Double } // Implementing specific shapes struct Rectangle: Shape { let length: Double let breadth: Double func area() -> Double { return length * breadth } } struct Triangle: Shape { let length: Double let height: Double func area() -> Double { return ((length * height) / 2) } } // Function to add areas of two different shapes using opaque type func sumOfArea(rectShape: some Shape, triShape: some Shape) -> Double { return rectShape.area() + triShape.area() } let obj1 = Rectangle(length: 10.2, breadth: 11.0) let obj2 = Triangle(length: 5.1, height: 6.0) let totalArea = sumOfArea(rectShape: obj1, triShape: obj2) print(“Total Area is : (totalArea)”) Output It will produce the following output − Total Area is : 127.49999999999999 Boxed Protocol Type A boxed protocol type is used to warp a type that conforms to a protocol inside a container. It generally uses a generic type or existing type like “Any”. It allows us to work with values of different types that share a common protocol without showing the underlying types. Example Swift program to demonstrate opaque type. // Define a protocol protocol Display { func details() -> String } // Implementing for specific types struct Student: Display { var name: String func details() -> String { return “Student”s Name: (name)” } } struct Teacher: Display { var tname: String func details() -> String { return “Teacher”s Name: (tname)” } } // Wrapper type for boxed protocol struct BoxedDisplay { let x: Display init(_ x: Display) { self.x = x } } // Function that accepts a boxed protocol type func displayDetails(box: BoxedDisplay) { print(box.x.details()) } // Instances let obj1 = Student(name: “Monika”) let obj2 = Teacher(tname: “Mohit”) let box1 = BoxedDisplay(obj1) let box2 = BoxedDisplay(obj2) displayDetails(box: box1) displayDetails(box: box2) Output It will produce the following output − Student”s Name: Monika Teacher”s Name: Mohit Difference Between Opaque Type and Boxed Protocol Type Following are the major differences between opaque type and boxed protocol type − Opaque Type Boxed Protocol Type It uses some keyword to create opaque type. It uses wrapper type to create boxed protocol type. It allows function to hide its return type. It allows function to return a concrete type wrapped in a container. It provide type erasure. It may or may not have type erasure. It hides the concrete type. It warps the specific type. Print Page Previous Next Advertisements ”;