{

Learn free swift tutorials


Array random shuffle in swift with example

February 28, 2022 ·  2 min read

Array elements are ordered based on the insertion order of elements. The elements can be retrieved on the index. Sometimes, array elements shuffle randomly and access it using an index. shuffle an array means, the elements in the original array reset their’ position randomly There are many ways we can do it. Swift Array Shuffle example Swift 4 version provides two methods. shuffle method: This shuffles elements in random order by modifying the original array....


Convert Dictionary to Array of keys and values example in swift

February 28, 2022 ·  2 min read

This tutorial explains how to convert key and value arrays from a dictionary in Swift. Dictionary is a type that stores the key and values of a given type. It is similar to Hashtable in storing keys and values in java. Dictionary is unordered, so the output of keys and values in an array are unordered. In Swift, there are two types for storing key and value pairs. Dictionary: It is a struct that contains a specific type in swift language....


Difference between == and === in the swift example

February 28, 2022 ·  2 min read

In Swift, there are two equal operator types. Double equal (==) and double not equal (!=) operator Triple equal (===) and triple not equal (!==)operator Swift Identity operator Double equal operator(==,!=) checks if two objects contains equal data or not. Triple equal operator(===,!==) checks if two objects reference is same or not. Here is an example of primitive types 22 === 1 // false 22 === 22 //true 22 == 1 // false 22 == 1 // false == checks the values are same, === checks values and reference type are same....


Find maximum and minimum elements in an array in swift with example| Dictionary

February 28, 2022 ·  1 min read

This tutorial is about finding maximum and minimum numbers from an array of numbers in swift for example. Maximum and minimum elements of an array using max and min functions Maximum and minimum elements of a dictionary using max and min functions How to find maximum and minimum numbers in an array of numbers in swift There are multiple ways we can find max and min in swift. use Array max, min method Array provides the max method that returns the maximum element from an array The min method returns the minimum element from an array....


Get Current Unix Epoch Time in Swift with examples

February 28, 2022 ·  2 min read

This article, Shows how to get the Current Timestamp or Unix Timestamp, or epoch timestamp in Swift. We will use one of the below methods NSDate.timeIntervalSince1970 Date().timeIntervalSince1970 CFAbsoluteTimeGetCurrent() + kCFAbsoluteTimeIntervalSince1970 Epoch timestamp or Unix timestamp is a long number in milliseconds to refer to a time of a day. It is a Count of milliseconds elapsed since 1970-01-01 UTC. How to get the Current Unix Epoch timestamp in Swift There are multiple ways to get the Current Timestamp in Swift....


How to calculate the sum of all numbers or object values in Array swift with an example

February 28, 2022 ·  2 min read

In this tutorial, learn how to find the sum of an array of elements. array reduce method with primitive and objects of an array The array can contain numbers or objects that contain numeric values. Array reduce method that takes an array of elements, and returns a single value. Sum of an array of numbers in Swift with examples The array has a reduce method that reduces the array of elements into a single value....


How to check if a string contains a substring in Swift with example

February 28, 2022 ·  1 min read

This tutorial explains how to check substring exists in a string in swift with examples For example, If a given string is cloudhadoop, substring cloud returns true. How to check if a string contains a substring in Swift? use contains in Swift 4 & 5 versions The string has contain a method that takes substring and returns true if found, else returns false. It does not check case sensitive substrings...


How to check if an element is in an array in the swift example

February 28, 2022 ·  2 min read

This post is about checking if an element exists in an array in swift with examples. It also includes checking object exists in an array of objects based on property. Array Contains method to check an item exists in an array Array Filter method to filter elements from an array, return an element if found. Check object exists in the Array of Objects using the filter method How to check if an element exists in a swift array with examples?...


How to Check if key and value exist in swift with example

February 28, 2022 ·  2 min read

This tutorial explains how to check the key and value that exists in a Dictionary in Swift. Dictionary is a data storage in swift to store keys and values. Let’s declare a dictionary with a key of Int and a value of String let emp: [Int: String] = [1: "john", 2: "franc", 3: "andrew"] How to find if the key exists in a dictionary or not in Swift In Swift, Dictionary[key] returns Optional value if exists else returns nil....


How to check the element index of a list or array in the swift example

February 28, 2022 ·  2 min read

This tutorial explains how to find the index of an element in an array of swift programming languages. Below, Shows the find the index of an element type. primitive array Array of Objects Array provides two methods [firstIndex](https://developer.apple.com/documentation/swift/array/firstindex(of:)) and [lastIndex](https://developer.apple.com/documentation/swift/array/lastindex(where:)) that returns the index position forward iteration and reverse iteration. Both methods return nil if no element is found in an array. How to find the element index for an array of numbers in swift The array contains a list of strings....


How to convert array into a string by delimiter in swift example

February 28, 2022 ·  2 min read

This tutorial explains multiple ways to convert an Array of elements into a String in Swift with examples. There are multiple ways to convert Array into a String use Joined function map with joined function Array map with reduce function Sometimes, We have an array of strings that you want to combine using a separator. This tutorial helps you with multiple ways to combine it. Convert Array into a String with delimiter in Swift There are multiple ways we can do it....


How to Convert Array to Set in swift with example

February 28, 2022 ·  2 min read

Array and Set are both data structures used to store a collection of elements. Let’s see some differences between Array and store Arrays: Array stores the duplicate elements It stores the elements in insertion order. Set: Set stores unique elements or objects Order is not guaranteed Set uses hashing values to store the objects, Hence retrieving the elements is faster compared to Array. This tutorial explains multiple ways to Convert Array to a Set in swift with an example...


How to convert Data to/from Hexa decimal string in the swift code example

February 28, 2022 ·  1 min read

This tutorial explains about following things in Swift Convert Data to Hexa decimal String Hexadecimal String to Data with example Sometimes, We need to convert Data to/from Hexa string in Swift. Data contains a string representation of bytes Hexa is a string that contains 0 to 9 and a to g. How to convert Data to Hexa decimal String in swift In this example, Convert data to a Hexa decimal string...


How to Convert Float to Int in swift with example

February 28, 2022 ·  2 min read

Int contains numbers without decimal values. Example int values are 45,7. The float contains numbers with decimal floating values. Example float values are 123.11,56.77. Int and Float are inbuilt types in Swift language. This tutorial explains multiple ways to convert Float to Int and Int to Float in Swift with examples How to Convert Int to Float in swift Swift Float has a constructor that takes int number You can check variable type in swift using the type(of:) function....


How to Convert String to Int in swift with example

February 28, 2022 ·  2 min read

This article talks about three ways to convert String to Int or String to Int in Swift Language. Convert String to number in Swift use the Int constructor. Convert number to String in swift String constructor String interpolation syntax double description String and Int are different data types and hold different values. When we want to perform mathematical calculations on strings that contain numbers, we must convert string to int....


How to Convert String to/from Double in swift with example

February 28, 2022 ·  3 min read

This article talks about multiple ways to convert String to Double or String to Double in Swift Language. Convert String to Double in Swift use the Double constructor. atof method NSString doubleValue Convert Double to String in swift String format String constructor String interpolation syntax double description String and Double are different data types and hold different values. When we want to perform mathematical calculations on strings that contain double numbers, we must convert string to double....


How to convert the String into an array in swift example | Xcode example

February 28, 2022 ·  1 min read

Sometimes, We want a string to be split into substring and converted into an array. The string can be split based on a delimiter such as space or comma. How to convert String into an array in swift use String components with the separatedBy attribute. String components method that takes separatedBy attribute, converted to an array. It works in the Swift 3 version only. import Foundation let str : String = "first middle last"; let strArray = str....


How to declare multi-line string literal in swift with example

February 28, 2022 ·  2 min read

In Swift, Normal strings are literals enclosed with double quotes. if you declare a multi-line string literal with a double quote. It throws an error var str:String = "first line second line" Output throws compilation error given below main.swift:1:18: error: unterminated string literal var str:String = “first line ^ main.swift:2:32: error: unterminated string literal second line” ^ main.swift:2:27: error: consecutive statements on a line must be separated by ‘;’ second line" ^ ; main....


How to do merge or append two arrays in swift example

February 28, 2022 ·  3 min read

This blog solves the below problems for developers How to merge two arrays in swift Concatenate or append or combine two arrays in swift Merging two arrays is an append either into the new array or one array into another array. Once arrays are merged, The same order appears as in the order of merge. var array1 = [11, 12, 13] var array2 = [21, 22, 23] result is [11, 12, 13, 21, 22, 23] There are multiple ways we can do merge...


How to find Length of a String in swift with example

February 28, 2022 ·  2 min read

The string contains a group of characters. Characters can be normal alphabets or Unicode characters. The length of a string is a count of the number of characters in a string. For example, If a string is “abc”, Then the length of a string is 3. Length of a String in Swift There are two types of a string. One is a String of normal alphabets without Unicode and emoji characters The second type of string contains Unicode characters....


How to find the length or count of a Swift Enum with example

February 28, 2022 ·  1 min read

An enum is a group of case statements with fixed values. This tutorial explains the length of a Swift Enum enum WeekEnd { case Saturday case Sunday } print(WeekEnd.count) It throws an error main.swift:6:15: error: type 'WeekEnd' has no member 'count'. There is no method count in swift e Swift Enum count cases There are multiple ways to get the count of cases in a swift enumeration. using CaseIterable protocol add CaseIterable to enum and It provides an allCases function that returns a sequence of collection of enum cases....


How to generate UUID in the swift example

February 28, 2022 ·  1 min read

There are multiple ways to generate UUID in swift with examples. NSUUID() class UUID structure Unique identifiers are 128-bit values that store unique values. There are different types of aliases Universally Unique Identifier(UUID) Globally Unique Identifiers(GUID) Interface Identifiers(IID) These unique identifiers are used to represent the primary key of an object in the database UUID follows RFC 4122 Version2 always generates a Unique string in lower case. These are written with base 16, and use 1-9 and a-f characters....


How to get Current Date and Time in Swift with examples

February 28, 2022 ·  2 min read

This tutorial explains how to get the Current Date and time in Swift with examples. Current Date and time in Swift using Date() function current Date in Short Format using DateFormatter.setLocalizedDateFormatFromTemplate("MM/dd/yyyy") get Time without Date using DateFormatter.long property How to get the Current Date and time in Swift? Date class provides an access to the date and time of UTC timezone. Here is an example import Foundation let date = Date() print(date) 2022-10-30 11:16:49 +0000 The date object returns the format as per the code running on the device or web....


How to get Current, Previous, Tomorrow's Date, and Time in Swift with examples

February 28, 2022 ·  1 min read

This tutorial explains getting the date and time in local, UTC, and timezone in swift Current Date Tomorrows Date Yesterday Date How to get Today, yesterday and Tomorrow Local Date and time in swift First, get the Current Date. Next, pass the current date Calendar. date function with byAdding=.day and value is one day. -1 day is used to pass Here is an example import Foundation; let todayDate = Date() var tomorrow = Calendar....


How to get the nth character of a string in Swift example

February 28, 2022 ·  2 min read

Sometimes, It is required to get a particular character from a given string. You can get using the index in a java programming language. The same does not work in a swift let message = "Hello world!" print(message[0]) It throws an error main.swift:2:7: error: ‘subscript(:)’ is unavailable: cannot subscript String with an Int, use a String.Index instead. print(message[0]) ^~~~~~~~~~ Swift.String:3:12: note: ‘subscript(:)’ has been explicitly marked unavailable here public subscript(i: Int) -> Character { get }...


How to get the top 5 elements from an Array swift example

February 28, 2022 ·  2 min read

Sometimes, We want to return to elements from an array as a subarray. subarray is a slice of an array. There are multiple ways to do this. How to return top elements as slice array in Swift using the range operator in Swift Swift provides a range operator(a…b) that contains start and end values and provides this to an array to get a subarray. the end value of the range operator is always less than equal to the array length...


How to print an array of objects in swift with example

February 28, 2022 ·  2 min read

Multiple ways to print an array of objects in swift code examples Iterate array using for loop and print an object, each object overrides description method dump method Sometimes, We have an array of objects and want to print the object values for debugging purposes. For example, Let’s declare an object of a Student class import Foundation class Student { var marks: Int = 0 var id: Int; init ( _ id: Int, _ marks: Int){ self....


How to remove an element from an array in swift with example

February 28, 2022 ·  2 min read

This tutorial shows you multiple ways to delete an element from an Array in Swift. How to remove an array element with an index? How to remove the first element from an array How to remove the last element from an array. Array in swift provides the following methods to remove an element. remove at method filter method removeFirst method removeLast method How to remove an array element in Swift?...


How to Sort Array of objects in ascending and descending order in swift with example

February 28, 2022 ·  2 min read

This tutorial explains how to sort an array of objects with properties in ascending or descending order. First, create a class and implements CustomStringConvertible, and provide an implementation for the description method. the description is used to print an object when an object is used for print to the console. import Foundation class Employee : CustomStringConvertible { var id: Int; var name: String; var salary: Int = 0 init ( _ id: Int, _ name:String, _ salary: Int){ self....


How to Split a String by separator into An array in swift with example

February 28, 2022 ·  1 min read

This article explains about multiple ways to split a string into array in swift 2,3 and 4 with examples How to Split the string by spaces in Swift? There are multiple ways we can do In the Swift 2 version, You can use the componentsSeparatedByString of a string. It returns an array of substrings. import Foundation var name: String = "Hello Welcome to cb " let substrings = name.componentsSeparatedByString(" ") print(substrings[0]); print(substrings[1]); print(substrings[2]); In The Swift 3 version,...


How to trim a string in Swift with examples

February 28, 2022 ·  3 min read

The string contains spaces at the start or end of a string. This post explains about following things. Trim whitespace in a string Delete leading space in a string remove trailing space in a string Remove a string that contains spaces in the middle or any. String trim whitespace example This example removes leading and trailing spaces from a given string. The trimmingCharacters method with whitespaces works in Swift version > 4....


Multi dimensional arrays swift with example

February 28, 2022 ·  4 min read

{{ }} An array of the array is also called a matrix, also called a two-dimensional array. You can create multi-dimensional in multiple ways. It contains multiple sub-arrays based on dimension. Let’s see some examples of multiple-dimensional arrays. How to create an empty two-dimensional Array Arrays can be fixed or dynamic. Let’s first create an empty two-dimensional array. The below array contains an array of integers. The first syntax is declared empty with a type declaration on the right side In the second syntax, if you are assigning empty brackets, you need to declare the type...


Multiple ways to add an element to an array in swift with example

February 28, 2022 ·  2 min read

This tutorial shows multiple ways to add an element to an array in swift with examples. add an element to end of an array using append method. [1,2].append(3) returns [1,2,3] Add an element at index position using insert method. [11,12].insert(2,0) adds an element at index=0, returns [2,11,12] += operator that adds element to end. ["one", "two"]+=["three"]returns ["one", "two","three"] An array is a group of elements with the same type. Each element is accessed with an index....


Multiple ways to create an array filled with repeated values in the swift example

February 28, 2022 ·  2 min read

This tutorial shows you multiple ways to create an array with the same values in an array of Swift for example. It is very useful to initialize repeated values in Development to learn and test array methods. How to create and initialize an array with the same values? There are multiple ways we can do this. It uses repeating and count syntax to create an value repeating is a repeating value in an array....


Multiple ways to create an array with incremented values in the swift example

February 28, 2022 ·  2 min read

This tutorial shows you multiple ways to create an array with incremented values or a range of values in Swift for example. It is very useful to initialize increased values in Development to learn and test array methods. How to create and initialize an array with incremented values? There are multiple ways we can do this. One way is Notation operator (…) It contains a range of values with start and end and both are included....


Multiple ways to flatten an array in the swift example

February 28, 2022 ·  1 min read

Multiple ways to flatten an array in swift with code examples Array reduce function Array joined function Array flatMap function The array contains a sequence of elements and it contains different dimensions. Flattening is a process of converting or reducing a multiple given dimensions array into a single dimension. Flatten an array of the array is converted to an array. For example, Given an array of arrays as given below...


Multiple ways to iterate a loop with index and element in array in swift

February 28, 2022 ·  2 min read

This tutorials shows multiple ways to iterate an array with index. Swift provides collection type such as Arrays, sets, and dictionaries. Let’s see an example for multiple ways to iterate an loop with index and an element in Swift array. How to iterate a loop with index an element in Swift Array? We use for loop to iterate an element in swift for-in loop iterates the loop for number of elements in an array....


Multiple ways to parse to absolute number swift with code example

February 28, 2022 ·  2 min read

This tutorial explains how to calculate the absolute value of a number in swift programming. abs() function for Int type fabs() function for Double type fabsf() function for Float type Int magnitude The absolute value of a number returns a number by removing the negative sign. For example, The input number is -123, And the absolute value is 123. if the number is 11 and the absolute value is 11....


prints Class object description with example| Java equivalent toString method

February 28, 2022 ·  2 min read

In Java, We have a toString method, prints the hashcode with classname by default, You can customize this method to print object properties and values. In Swift, The same is not available Let’s declare a class import Foundation class Employee { var id: Int; var name: String; var salary: Int = 0 init ( _ id: Int, _ name:String, _ salary: Int){ self.id=id self.name = name self.salary = salary } } Next, Create an object and print it...


Random Generator in swift with example

February 28, 2022 ·  2 min read

This tutorial shows multiple ways to generate random generators in Swift with examples. Generator Random Number between 1 and 10 In Swift, Each primitive type has a static random function. Int.random Float.random Double.random Bool.random() These types of functions returns a random value. Let’s see an example to generate a random number for the Int class. static func random(in: Range<Self>) -> Self The range contains below types. m...n which is inclusive of m and n m....


Remove Duplicate elements from an array in swift with an example

February 28, 2022 ·  1 min read

This tutorial explains different ways to remove duplicate elements from an array with code examples Convert Array to Set using Set(array), again convert to Array using Array(Set) Iterate an array and add element to an set, convert to array. For example, the Input array contains the following elements array=[1,11,1,2,3,1,3] 1 and 3 are repeated and removed from an array, the following is an array. Output: array=[1,11,2,3] How to remove duplicate elements from an array in Swift with examples There are multiple ways we can remove duplicate elements....


Round double value with n number decimal places in the swift example

February 28, 2022 ·  2 min read

It is a common requirement to display prices and orders with a limit of 3 decimal places. This tutorial explains how to round double values to limit decimal places. There are multiple ways we can limit decimal places. For example, If the input is 123.456789, the output is 123.456. How to round double values to limit decimal or fraction parts in Swift? Following are ways to round double fractional parts...


Swift Add day, week, month, and year to the current date in the example

February 28, 2022 ·  2 min read

This tutorial shows how to do the following things in Swift Get Yesterday’s date Get Tomorrow’s date Add and subtract 1 week to the Current date Add and subtract 1 month to the Current date Add and subtract 1 year to the Current date To add any value to the Current Date, Calendar provides the date method with the below syntax date(byAdding:to:options:) byAdding: tells to add .day or .month,.year and ....


Swift if Given date is before Current Date with example

February 28, 2022 ·  1 min read

This tutorials shows if given date is before current date or today. The below examples check only Dates, not time Check if given date is before today date in swift? Current date returns using new Date() object. You can create past and future date using date method It accepts byAdding: tells to add .day or any value: value can be positive or negative to: specify current date. Dates can be compared using < operator...


Swift Tutorial How To Set & Get Swift Properties

February 28, 2022 ·  1 min read

Swift language provides setter and getter to the class properties to achieve Encapsulation. The class contains properties and the instance of a class contains properties and variables. Usually, The properties of an object are set using the constructor. These will be initialized at the object creation level. How do you set the properties of an object? Using setters and getters allows you to set and get the property data after the instance is created....


Subscribe
You'll get a notification every time a post gets published here.