Any programming language's data type consists of a set of information with set meanings and distinctive variables. You must use different types of variables to store information while programming in any programming language. Variables are nothing more than reserved storage locations. This means that you reserve some space in the memory when creating a variable.
You can save information on different types of data like strings, characters, widespread characters, integer, boolean, etc. The operating system allocates memory on the basis of a variable data type and decides what is stored within the storage space.The Swift language provides different kinds of data types. The following are some of them:
This is an ordered character set. "Hi, World!" for instance.You can create a String either by using a string literal or creating an instance of a String class as follows −
// Example String literal var stringX ="Hello, World 1!" print( stringX ) // Example String instance var stringY =String("Hello, World 2!") print( stringY ) //Example Multiple line string let stringZ =""" Hey this is a example of multiple Line string """ print(stringZ) The output for the above programme would be as follows: Hello, World 1! Hello, World 2! Hey this is a example of multiple Line string
Now we will discuss some scenarios for string data type
You can create an empty string either through a literal empty string or by creating a string class instance as shown below. The boolean property isEmpty can also be used to check whether the string is empty.
// Example String literal var stringX = "" if stringX.isEmpty { print( "stringX is empty") } else { print( "stringX is not empty") } // Example String instance let stringY = String() if stringY.isEmpty { print( "stringY is empty") } else { print( "stringY is not empty") }
You can indicate whether your string can be changed by assigning it to a variable or whether it is constant by assigning it to a constant by the keyword let as shown below.
// stringX can be modified var stringX = "Hello, World!" stringX + = "--Example--" print( stringX ) // stringY can not be modified let stringY = String("Hello, World!") stringY + = "--Example--" print( stringY )
The above program will give compilation error as we are trying to modify the second string which has been declared as constant.
Playground execution failed: error: <EXPR>:10:1: error: 'String' is not convertible to '@lvalue UInt8' stringY + = "--Example--"
String interpolation is a way to construct a new string value by including the value within a literal string from a mix of constants, variables, literals and expressions.
var varX = 30 let constX = 20 var varY:Float = 20.0 var stringX = "\(varX) times \(constX) is equal to \(varX * 20)" print( stringX ) The output would be: 30 times 20 is equal to 600.0
You can configure two strings or strings and a character or two characters with + operator. An easy example is here −
let constX = "Hello," let constY = "World!" var stringX = constX + constY print( stringX)
Swift strings have no length property, but you can count the number of characters in a string using the global count () function.
var varX = "Hello, World 4!" print( "\(varA), length is \((varA.count))")
The== operator can be used to compare two string variables or constants strings. This is a straightforward instance −
var varA = "Hello, World!" var varB = "Hello, World!" if varA == varB { print( "\(varA) and \(varB) are equal") } else { print( "\(varA) and \(varB) are not equal") } Swift promotes a broad variety of string-related methods and operators.
Sr.No | Functions/Operators & Purpose |
---|---|
1 | isEmpty A Boolean value which tells whether or not a string is empty. |
2 | hasPrefix(prefix: String) Function to verify if a specified string is available as a string prefix or not. |
3 | hasSuffix(suffix: String) The function of checking if a particular string parameter exists as a string suffix or not. |
4 | toInt() Function to convert numeric String value into Integer. |
5 | count() Global character counting function in a string. |
6 | utf8 Returning property of a string UTF-8 representation. |
7 | utf16 Returning property of a string UTF16 representation. |
8 | unicodeScalars Property to return a string representation of Unicode Scalar. |
9 | + Two strings or one string and one character or two characters are connected by an operator. |
10 | += Operator for a current string to attach a string or character. |
11 | == Two-string equality determination operator. |
12 | < Operator to conduct a lexicographical comparison to determine if one string is less than another. |
13 | startIndex To get the value at starting index of string. |
14 | endIndex To get the value at ending index of string. |
15 | Indices To access the indices one by one. i.e all the characters of string one by one. |
16 | insert("Value", at: position) To insert a value at a position. |
17 | remove(at: position) removeSubrange(range) to remove a value at a position, or to remove a range of values from string. |
18 | reversed() returns the reverse of a string |
This is a literal string of one character. "F" for instance.
let char1:Character="X" let char2:Character="Y" print("Value of char1 \(char1)") print("Value of char2 \(char2)")
If you attempt to store multiple characters in a Character type variable or constant, Swift will not allow that. In Swift you will try to write the instance below, and even before compilation you will get an error.
// Trying to store multiple characters letchar: Character = "AB" print("Value of char \(char)")
Also It is not possible to create an empty Character variable or constant which will have an empty value.
// Following is wrong in Swift let char1: Character = "" var char2: Character = ""
As described, string reflects a collection in a defined order of character values. Thus we can use a for-in-loop iteration to access individual characters on the specified string.
for ch in"Hello World" { print(ch) }
The following instance shows how a string can be combined with a character.
var varX:String = "Hello " let varY:Character = "W" varX.append( varY) print("Value of varZ = \(varX)")
Swift arrays are used in ordered lists of any particular sort to store various values.Swift establishes strict control mechanisms that enable programmers not to enter or insert any false types into an array even by mistake, i.e., arrays in swift programming are specific about the kinds of values they can store.In a swift array at distinct locations, the same value may occur. The swift arrays vary from the NSArray and NSMutableArray classes of Objective-C which can store any item and provide no information on the nature of the objects it returns. In Swift it is always evident what sort of values a specific array can store, either via an explicit type annotation or a type inference, without having to be a class form. Swift arrays are secure, and what they may contain is always evident.
The swift array can be represented in the format as the array < SomeType > in which the array will be stored as' SomeType.' Programmers can also write an array type as SomeType[] shorthand. While the two forms mentioned are functionally the same, the shorter form is preferred rather than the other. If programmers assign a variable to an already current array, it is always changeable. This implies that the programmer has the option to alter it, add, delete or alter its elements. But when a constant is assigned to the arrays, the array is immutable and cannot change its size and content.
The following initializer syntax allows you to generate an empty array of a certain type. −
var someArray = [SomeType]()
This is the syntax for the creation, initialisation and value of an array of a given size a* −
var someArray = [SomeType](count: NumberOfElements, repeatedValue:InitialValue)
You can create an empty Int-type array with three elements and the initial value as zero with the following statement. −
var someInts = [Int](count: 3, repeatedValue:0)
Following is one more example to create an array of three elements and assign three values to that array −
var someInts:[Int] = [10, 20, 30]
By using a subscription syntax, you can get a value from an array and instantly after you get an index of the value that you want to recover from the array.
var someInts =[Int](count:3, repeatedValue:10) var someVar = someInts[0] print("Value of first element is \(someVar)") print("Value of second element is \(someInts[1])") print("Value of third element is \(someInts[2])")
You can add a fresh object on the end of an array using the append or the addition of an assignment operator (+ =). Check out the example below. We generate an empty array here at first, and then add fresh components to the same array.
var someInts = [Int]() someInts.append(20) someInts.append(30) someInts += [40] var someVar = someInts[0] print( "Value of first element is \(someVar)") print( "Value of second element is \(someInts[1])") print( "Value of third element is \(someInts[2])")
To find out whether or not an array is emptied, you may use the read only empty property of an array.
var intsA = [Int](count:2, repeatedValue: 2) var intsB = [Int](count:3, repeatedValue: 1) var intsC = [Int]() print("intsA.isEmpty = \(intsA.isEmpty)") print("intsB.isEmpty = \(intsB.isEmpty)") print("intsC.isEmpty = \(intsC.isEmpty)")
To find out the following numbers of items in an array, you can use the read-only count property of an array.
var intsA = [Int](count:2, repeatedValue: 2) var intsB = [Int](count:3, repeatedValue: 1) var intsC = intsA + intsB print("Total items in intsA = \(intsA.count)") print("Total items in intsB = \(intsB.count)") print("Total items in intsC = \(intsC.count)")
You can combine two arrays with the same type using the addition operator (+) to create a fresh array with a mix of values from both arrays as follows.
var intsA = [Int](count:2, repeatedValue: 2) var intsB = [Int](count:3, repeatedValue: 1) var intsC = intsA + intsB for item in intsC { print(item) }
You can use enumerate() to return the index and value of an item, as shown in the following example.
var Strs = [String]() Strs.append("India") Strs.append("Srilanka") Strs += ["Pakistan"] for (index, item) in Strs.enumerated() { print("Value at index = \(index) is \(item)") }
The output of the above program would be as follows:
Value at index = 0 is India Value at index = 1 is Srilanka Value at index = 2 is Pakistan
Specific values of the same type are stored in Swift sets, but they don't have definite arrays as ordered.
You can use sets rather than arrays when there is no problem with ordering components or if you want to make sure no duplicate values are present. A type must be hashable to save in a set. (Sets only enable distinct values). A hash value is an Int value that is equal for equal objects. For Example When x= y, then x.hashvalue== y.hashvalue .
All the fundamental Swift values can be used as set values and are by default hashable.
Use the following initializer syntax to produce an empty set of a certain type.
var someSet = Set<Character>() //Character can be replaced by data type of
Set.
Use its methods and properties to access or change a set.
someSet.count // prints the number of elements someSet.insert("c") // adds the element to Set. someSet.isEmpty // returns true or false depending on the set Elements. someSet.remove("c") // removes an element , removeAll() can be used to remove all element someSet.contains("c") // to check if set contains this value.
for items in someSet { print(someSet) } //Swift sets are not in an ordered way, to iterate over a set in an ordered way use for items in someSet.sorted() { print(someSet) }
Some operations on Sets
let evens: Set = [10,12,14,16,18] let odds: Set = [5,7,9,11,13] let primes = [2,3,5,7] odds.union(evens).sorted() // [5,7,9,10,11,12,13,14,16,18] odds.intersection(evens).sorted() //[] odds.subtracting(primes).sorted() //[9, 11, 13]
The unordered list of values of the same sort is type stored in dictionaries. Swift makes stringent controls that do not allow you to erroneously enter a false type into a dictionary.
Swift dictionaries use a unique identifier called a key, which can then be referenced and viewed by the same key. Unlike array items, array items have no order in a dictionary. When you have to look for values on the basis of your identifiers, you can use a dictionary.
An integer or a string may be a dictionary key, but it should be unique within a dictionary.
If a generated dictionary is assigned to a variable, it is always mutable that allows you to alter it by adding, removing or modifying its objects. But if you give a dictionary a constant, it is immutable and cannot change its size and content.
var someDict = [KeyType: ValueType]()
Example
Empty Dictionary
var someDict = [Int: String]()
Dictionary with set of values
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
A below example displays how we can use array to declare Dictionary(key-value) pair.
var cities = [“Patna”,”Chennai”,”Kolkata”,”Bangalore”] var Distance = [3000,2500, 620,700] let cityDistanceDict = Dictionary(uniqueKeysWithValues: zip(cities, Distance))
The above program will create a dictionary with cities as key and distance as value.
We can run below program for filtering cities having distance less than 1000.
var closeCities = cityDistanceDict.filter { $0.value < 1000} The output would be ["Kolkata" : 620, "Banglore" : 700]
We can also apply grouping in dictionary with below syntax. If we would like to group cities based on first alphabet.
var cities = ["Delhi","Bangalore","Hyderabad","Dehradun","Bihar"] var GroupedCities = Dictionary(grouping: cities ) { $0.first! }
Then output would be
["D" :["Delhi","Dehradun"], "B" : ["Bengaluru","Bihar"], "H" : ["Hyderabad"]]
By using a subscription syntax, you can recover a value from a dictionary by passing the value key you want to collect from the dictionary right after the dictionary name.
var someVar = someDict[key]
To add current value to a specified dictionary key, you can use updateValue(forKey:) technique. This technique returns an optional value of the type of value of the dictionary.
var someDict:[Int:String] = [1:"hello", 2:"World", 3:"Example"] var oldVal = someDict.updateValue("New value of one-hello", forKey:1) var someVar = someDict[1]
print( "Old value of key = 1 is \(oldVal)") print( "new Value of key = 1 is \(someVar)") The output would be Old value of key = 1 is Optional("hello") Value of key = 1 is Optional("New value of one-hello")
To remove a key value pair from a dictionary, you can use the removeValueForKey() method. This technique removes the key value pair, if it exists, and returns the deleted value.
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"] var removedValue = someDict.removeValue(forKey: 2) //There is an alternative way as well someDict[2] = nil print( "Value of key = 2 is \(someDict[2])") The output would be Value of key = 2 is nil
The whole series of key value pairs of a dictionary can be iterated using a for-in loop, as shown in this example.
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"] for (index, keyValue) in someDict.enumerated() { print("Dictionary key \(index) - Dictionary value \(keyValue)") } The enumerate() method can be used to return the index of the item along with its (key, value). var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"] for (key, value) in someDict.enumerated() { print("Dictionary key \(key) - Dictionary value \(value)") }
Summary:
This module gave us fair idea of inbuilt data types being used in swift. We have found similarities in swift data types with other programming language data types. Swift has also similar data types for strings ,characters ,array ,sets and dictionaries.
I am interested in the learning of swift and coding
Is this included in csm training and certification or sold separately?
I am interested in advanced level training of SWIFT and coding.
C# is an object-oriented programming developed by Microsoft that uses ...
Leave a Reply
Your email address will not be published. Required fields are marked *