Swift operators

As we all know operators are the basic and fundamental concepts in any programming languages. In Swift, operators are same as other programming language operators, but Swift operators are more efficient and simplified than other languages which help developers using it efficiently. let’s go through operators, then on the go lets see the swift specific operators. Is it boring? if so, please bear with me.

For what we need operators and what is the purpose of it?. Simple, manipulating the values and checking the multiple variables and decide the flow of the code using decision-making syntax.

Operators are Unary, binary and ternary.

Unary Operator:

Unary operators work on a variable. Explaining by words will rotate our brain in 360 degrees. right.. let’s see an example for unary operators
lets say boolean variable ‘a’ is there, and we want to change the state of it, like true to false or vice versa.
a = !a
So here, ‘!’  is an unary operator, which operands on a variable named ‘a’.
Similarly,
a = -a
where, ‘-‘ operator changes it to a negative value if it is positive.

Hope that at this moment you could get the idea of binary operator

Binary Operator:

Nothing to explain in detail, as unary operator works on a single variable, a binary operator has two operands, wanna put one technical word, that’s why operands. So binary works on two variables like below
Addition -> a = a + b
Subtraction -> a = a - b
Multiplication -> a = a * b
Division -> a = a / b
Modulo -> a = a % b
Hope that, you can easily point the binary operators on the sample above, yes +,-,/,*% are the binary operators.

Ternary Operators:

Now hope that I need not explain about ternary operators, if I say again, like if an operator works on three operands then it is a ternary operator. You will throw a stone on me. But the sad part I have to say the same. please pick the small one. let’s see an example for that.

‘? :’ is a ternary operator, let’s take an example, we need to check the boolean, we need to print as true if it is true, or false if it is false.
how we will do generally using if condition.
Bool b = false
if b == true {
print("yes, it is true")
}
else{
print("no,it is false")
}
We have written six lines for that, how it would be if we use ternary operator and write the above case in a line. Simply superb right!!
(b == false) ? print(“yes,it is false”) : print(“no,it is false”)

Assignment Operator:

The assignment operator is to initialize or update the value of a variable.
below is an example for that let b = 10
As I said in the beginning of this tutorial, I am pointing the difference of assignment operator between C, objective C, and Swift.

in objective C
if a = b {
} // is valid, since it will return a value after assigning the value of b to a, but in Swift, the same condition is not valid since assignment operator in Swift never returns a value.

Arithmetic Operators:

Swift supports the four standard arithmetic operators
addition +
subtraction –
multiplication *
division /

Another significant thing in swift, I like to highlight here is, addition + operator also supports for String concatenation. we can see String in detail in next chapter.

Comparison Operators:

Like other programming languages, Swift supports following standard Comparison operators.

equal to (a == b )
not equal to (a != b )
less than (a < b)

greater than ( a > b)
less than or equal to ( a b)
greater than or equal to ( a b )

Identity operator:

Swift also provides identity operators which help to test whether two object references both refer to the same object instance.

Range operators:

Range operators are expressing of the range of values. Swift provides two type of range operators.

Closed Range operator
Half-Open Range operator.

Closed Range operator:

The syntax for closed range operators is a…b, it includes both a and b

for i in 1...5{
print(" i = \(i)")
}

Half Open Range Operator:

The half-open range operator( a..<b ) also defines a range that includes a but not includes b.

for i in 1..<5{
print(" i = \(i)")
}

the above example does not print the 5th value, as it does not include 5 in the range.

Logical operator:

Swift supports standard logical operators,
|| or operator
&& and operator

Nil-Coalescing Operator:

?? is nil coalescing operator, so what it does, it unwraps the variable to know the value and use it. If it does not have value, it sets nil. I can read your mind voice that expecting an example.

Lets assume

var a : String?

let b = a ?? “a is nil”

from the above example, our Nil-Coalescing operator checks the value of string a by unwrapping it and assign that value to b, if a is nil while unwrapping, it sets string as “a is nil” to b.

This is nice right, we read ternary operator to make use of if condition efficiently, now we are having a Nil-Coalescing operator which is more elegant way to encapsulate this conditional checking.

Force UnWrapping, Optional Chaining , Optional Binding – Swift 3

Before learning optional , it would have been better, if we have gone through Variables in Swift before.

Wrapping , UnWrapping in Swift

Optional values are the fundamental concept in Swift language, if a variable ends with ‘?’ in declaration, then it is an optional value(wrapping). Meaning of that it may or may not contain value for that. Bit confusing? lets see an example

let normalString : String = “variable without optional”

We have declared a constant string variable without optional ‘?’ , while printing below

print(normalString

it writes as “variable without optional“, now let’s see what happens if we use optional ‘?’

let optionalString : String? = “String variable with optional”

print(optionalString)

It prints as “Optional(“String variable with optional”). Hope that you can see the difference. Yes, Optional ‘?’ wraps the actual value, and if we need actual value of that variable, we need to unwrap it using ‘!’ , 

print(optionalString!)

 Now it prints as “String variable with optional”. I hope that now you got idea wrapping and unwrapping.

Force unwrapping:

Force unwrapping is nothing but an extracting the values from an optional ‘?’ variable . Ok, we aware that force unwrapping using exclamation mark ‘!’ will return a value. But how it will behave if it does not contain a value. Yes, it will make the application crash at run time. let’s see an example for that

var optionalString : String? // not assigning any value to this string data type

print(optionalString!) // here force unwrapping it.

then, the result in a playground is

fatal error: unexpectedly found nil while unwrapping an Optional value

Now we all got idea about wrapping(‘?’)  , unwrapping(‘!’) and now you will have a question, What is the purpose of it? and where can we use it efficiently?. That’s where optional chaining and optional binding comes.

Optional Chaining and Optional Binding:

let’s assume that we don’t have an optional feature in Swift, and I am creating an instance as ‘a’ for the class named ‘A’ like below. But I am not initializing it properly, just declaring it.

class A{

    let: String = "property in class A"    

}

let a : A

and I am accessing the property called ‘p’ which is there in that class ‘A’

print(a.p)

Now the playground gives me error and crashing with error

Optional chaining in Swift 3
Optional chaining in swift3

Playground execution failed: error: MyPlayground.playground:15:7: error: constant ‘a’ used before being initialized

Optional helps us to avoid this error and is playing a key role here. It avoids the app crashing at runtime though we forget to initialize the class object instance. Let’s take the same example again but with optional

class A{

    let: String = "property in class A"    

}

var a : A?

I am accessing the property called ‘p’ which is there in that class ‘A’

print(a?.p)

Now the app won’t crash, but it will print as ‘nil’. This feature in Swift is optional chaining. in the same case, if we do force wrapping it print(a!.p) without initialize then the app will crash.

We now have basic knowledge on optional chaining, wrapping, force unwrapping then what is that optional Binding?.

Optional Binding:

Optional Binding is to get the value from an optional variable to normal variable. let’s take a look at this example

var optionalString : String? = "String with '?' optional" // declaring optional string with value not nil

print(optionalString) // printing it without unwrapping , prints as “Optional(“String with \\’?\\’ optional”)\n”

if let getValue = optionalString { // here , we are getting the value from optionalString to getValue , i.e Optional Binding.

    print(getValue) // if value is there , then prints as "String with '?' optional"

}

else{

print("value is not there in optionalString") // if value is there , then prints as "value is not there in optionalString"

}

Hope that you have understood Optional Binding, Optional chaining, wrapping ‘?’ , force unwrapping ‘!’ in swift. Please share this tutorial across your circles and put your thoughts in the comment section as well.

Swift String Concepts

String is the special data type in programming languages, the sequence of characters is String. In Swift string variables are declared using String syntax.

And character is an element in String which is an another data type in a programming language.  In swift, character syntax is Character. Ok, don’t worry I won’t leave you without telling an example for that.You will get an example in the String mutability section.

Mutable, Immutable String:

String mutability is, how we can alter the string variable. if a string is declared with var keyword if you want to get to know about var and let, please check our variable and constants tutorial. Let’s come back to our point. If a string variable is declared with var keyword, then it is a mutable string which means we can change the value of that variable at any time like we have NSMutableString in Objective C. In Swift it is very simple right.

just declare as

var mutableString : String = “Mutable string as a keyword is var”

whereas if a string is declared with let keyword string, then it is constant and we can not change the value of that string object.

let immutableString: String = “String can not be modified”

This is just similar to NSString in Objective C.

if we try to change the value of the string, the compiler will throw an error.

immutableString = “modifying constant String” // compiler error for modifying constants.

whereas we can change the value of mutable string which is having var keyword.

mutableString = “i am able to modify var string” // compiler not saying any error.

Characters In String:

As we states earlier,string is a collection of characters , we can access characters in a string using for-in . I will write tutorial about for-in in control flow chapter soon.

let myString = “characters list”

for c in myString {

print(\(c)) // it prints character in that string one by one.

}

String interpolation:

String interpolation is nothing , constructing a string from multiple data type like int,character or other literal. Below is an example for that.

let interpolationStr = \(3) + \(2) = \(5)”

print(interpolationStr) // prints 3 + 2 = 5

where, 3 , 2 and 5 are Int.

String concatenation:

String concatenation is very simple in Swift, we have already mentioned this in operators chapter. Arithmetic plus ‘+’ operator can be used for string concatenation.

let concatString = “string1” + “string2”

print(\(concatString)) // prints as string1string2 as + concatenates both strings.

Is Swift String Unicode compliant?

Unicode is an International standard format, if a text file is not supporting that then it will not be recognized by other programming languages. It clears that Unicode is for reading, encoding text from different writing systems. Swift is also Unicode compliant.

How does this Unicode work? Unicode has some background strategy that each character will have a scalar value that is Unicode scalar. For example, U+0061 is for ‘a’.

Modifying the String:

Swift provides a couple of options to access or modify the strings. It could be either through methods or subscript.

First of all, we need to initialize the string,

let myFirstString = “”

let myString = String()

In both ways we can initiate the string, both are equal and has an empty string.

Empty String:

Swift provides a method to check if the string is empty or not. Below is an example for that

if myString.isEmpty {

    print(“String is Empty”)

}

isEmpty() method is used to check the empty string.

String Indices:

As we all know, the index is for pointing the position. Since string in a collection of characters, String has a property called index. An index gives the position of that character.

Three key points , we should keep in mind are startIndex , endIndex, offSetBy. Let me explain one by one .

startIndex gives you the first character position of the String, for example

let myString = “abcde”

if myString.isEmpty {

    print(“String is Empty”)

}

print(\(myString[myString.startIndex])”) // prints a

As String is a collection of characters , we are getting the first index using startIndex and accessing the first character from the String.

endIndex gives you the last character position of the String, for example

let myString = "abcde"

if myString.isEmpty {

    print("String is Empty")

}

print("\(myString[myString.endIndex])") // prints e

As String is a collection of characters, we are getting the last index using endIndex and accessing the last character from the String.

Note: please keep in mind that we can not access a character in String using integers

Thats why our next key word offSetBy comes here, which advances the index position from startIndex in the below example

print(\(myString[myString.index(myString.startIndex, offsetBy: 3)])”

Swift-string-learn
Swift String index and empty

The above print statement prints ‘d’ , since we are setting the offset value 3 from startIndex.

Hope that I have given the basic stuff about String in Swift. Please share and raise your feedback in comments

Collection Types in Swift

I am starting this Collection Type tutorial in the assumption that you have knowledge on Datatypes like int, string. If you want to refresh, please go through our Datatypes and String tutorial.

Lets come back to Swift Collection, it is used to store multiple values of the same type in a type. There are three types of collection in Swift 3.

  1. Arrays
  2. Set
  3. Dictionary

Arrays elements are ordered collection type, whereas Set and Dictionary are unordered collection ttypes,elements in Set and Dictionary are not ordered.

Another difference between Array and Set is, Array can have duplicated elements , but values are unique in Set.

Arrays:

As we said earlier, an array is an ordered collection type, and it can have same values in multiple index i.e duplicated values.

and declaration is Array<Element>, where Element is a type of the value that array is holding. We will see an example in next section.

Array Initialisation:

If you are from String tutorial in our last chapter, this will be easier for you to understand all the initialisation in Swift.

let myFirstArray : Array<Int> = [1,2,3,4]

in shorthand , we can initialize an array as  

let myFirstArray = [1,2,3,4]

Those two examples are constant arrays and we can not modify it since its keyword is declared as let.

Below is an example of creating an empty array and followed by its shorthand.

var mutableFirstArr = [Int]()

var mutableFirstArr = [] // shorthand empty array

Since it is declared with var, it is mutable and we can modify this array values at any time.

Accessing Arrays:

Accessing array is nothing but a getting the number of element from that array, get the value from particular index, modify the value at particular index, add or remove a value to/from an array

Let’s start with count,  let’s take our previous example back here

let myFirstArray = [1,2,3,4]

The number of elements that array stored can be read by count method.

print(myFirstArray.count) , it prints as 4, since it has 4 values such as 1,2,3,4

Empty Array:

To determine the empty state of an array, we can use count method again, if it is zero, then the array is not having any values.

Another simple method is there in Swift, isEmpty, to check the empty array. Here no need to check the count is equal to 0 or not, pretty simple right?.

if myFirstArray.isEmpty {

  print("array is empty")

}

else {

    print("array is not empty")

}

Add & Delete :

Another key factor in a programming language is to add an element of an array. append() in Swift help us to add a new value to an existing array at the end. Let’s take the same array but with var keyword, since we are going to change it by adding a value.

var mutableFirstArr = [1,2,3,4]

mutableFirstArr.append(5

Here I am appending number 5 at end of the array.

Alternatively, we can join two compatible type arrays using + operator easily.

mutableFirstArr += [6]

in the above line, I am adding an array that has single int element as 6 to an existing array.

We have knowledge now to add a value at the end, so next is to add value at the particular index.

mutableFirstArr.insert(0, at: 0)

The above example explains the insert method and takes an argument with at label that is the index position to insert the value in that array. Ok, Next thought in your mind would be deleting a value from an array. Am I right?

mutableFirstArr.remove(at: 5)

remove method that takes index position to delete the value from that position.

another short form to delete the last element of an array is removeLast().

Accessing array using Subscript:

To read or change a value from a particular position of an array, subscript syntax can be used. It is very simple to use.

mutableFirstArr[5] = 6

The above example replaces the value that is at the 5th position to a new value as 6.

Below is playground screenshot to brief our array tutorial.

Screen Shot 2017 04 15 at 10 27 54 PM

Array iteration:

An array can be iterated using for-in loops that we will see in future.

for i in mutableFirstArr{

    print(i)

}

Set:

Set in swift is more or less similar to an array. But the main difference between an array and a set is, duplicated values are not allowed in Set. And Set also performs set operations like join, intersection, union, symmetric difference.

The types that are going to be stored in Set must be hashable, in order to compute its unique value internally. If a type is not hashable, it can not be stored in Set.

Set Initialisation:

Set initialization is similar to Array, here also we have different types of initialization.

let myFirstSet : Set<Int> = [1,2,3]

let mySet = [1,2,3]

var firstSet = Set<Int>() 

Since we have explained this initialisation in Array section, assume that need not to explain again. “I am bit lazy 🙂 “

Accessing and Modifying a Set:

Set can be accessed using its methods and properties.

count property is to find out the number of items or elements in a set

print(myFirstSet.count)

Just like array, Empty set can be found using isEmpty property

if myFirstSet.isEmpty

{

    print("set is empty")

}

else {

    print("set is not empty")

}

Add or remove an item:

Insert method is useful for inserting an item in an existing set, It is similar to an array, but the difference here in insert method of a set is, it won’t ask you the index position to where it needs to be placed. Can you guess that why it is like that? yep, Set is an unordered collection type, and it places the item at any place.

var firstSet = Set<Int>()

firstSet.insert(1)

And to delete an item is also same,

firstSet.remove(1)

Set iteration:

Set also can be traversed through using for-in loops.

for i in firstSet{

    print(i)

}

Playground screenshot for giving a brief about Set.
Screen Shot 2017 04 15 at 11 15 24 PM

I will write detail tutorial for dictionaries in next chapter. Please share this tutorial if you feel that I have given at least some basic knowledge,  across your friends in social media and put your words in comment section to improve my skills

Dictionary – Swift 3

Dictionary is an another container/collection type in Swift.This tutorial gives the basic understanding of Dictionary or key value type.  Dictionary and Set both collection types are unordered types whereas Array is an ordered type, items in an array are in an order. Like String or Array, Dictionary tutorial also briefs initialization, declaration, accessing and modifying the dictionary.

“Dictionary is a key value pair data type, each value in a dictionary is associated with a unique value”. This key helps to access the value from the dictionary. And the items or elements in a dictionary can be in any order.

Dictionary Initialization:

Just like other types in Swift, Dictionary also has inferred and explicit declaration.

Below example does not specify its key, value type explicitly. Hence this type of declaration is inferred.

let inferredDict = ["gender" : "male" , "name" : "ProgramTeach"]

 The above declaration initializes the dictionary with two items. As both values in the dictionary are a String type, the compiler is not prompting the error to specify the type. let’s add age with Integer type value in the sample.

let inferredDict = ["gender" : "male" , "name" : "ProgramTeach" , "age" : 21] as [String : Any]

if you see the colored casting is to let the compiler know the type is dictionary having generic values. The below declaration is equal to that where we are explicitly specifying the Generic type in front.

let inferredDict :  [String : Any] = ["gender" : "male" , "name" : "ProgramTeach" , "age" : 21]

Dictionary Mutability:

Mutability is same as we have NSMutableDictionary and NSDictionary in Objective C. If a dictionary declared with let keyword, it is constant and its values can not be modified. The above samples are declared with let keyword. If a dictionary is declared with var keyword, it is mutable and value of that dictionary can be modified, new key value can also be inserted.

var inferredDict :  [String : Any] = ["gender" : "male" , "name" : "ProgramTeach" , "age" : 21] // now the keyword is var. 

We will extend this in next section called accessing / Modifying the dictionary:

Accessing a Dictionary:

As we said earlier, a unique key is to access the value from a dictionary as a subscript.

The returned value is optional since it may have value or not, Below optional binding helps to check value presence.

if let age = inferredDict["age"]{

    print(age)

}

else {

    print("age is not there")

}

There we are reading the age from that dictionary, if it has value for that key, it gives value.

Modifying a Dictionary:

Dictionary with var keyword is mutable. We can add, update or delete an item from the dictionary.

var firstDict :  [String : Any] = ["gender" : "male" , "name" : "ProgramTeach" , "age" : 21]

firstDict["age"] = 31 // updates the age

firstDict["address"] = "ProgramTeach , no 6 xyz street" // adds new entry to that dictionary

firstDict.removeValue(forKey: "gender") // removes an item gender from dictionary.

Empty Dictionary:

Empty dictionary means instance with zero entries that can be identified using isEmpty property.

if firstDict.isEmpty {

    print("empty dictionary")

}

To create empty Dictionary,

let emptyDict : Dictionary<String,String> = Dictionary<String,String>()

let shortEmptyDict = [String:String]() // short form

Playground screenshot for covering this tutorial.

Swift Dictionary

Please share and drop your thoughts in comment section.

Which programming language will be in great demand in the future?

Which programming language will be in great demand in the future? by Venkat Prabhu

Answer by Venkat Prabhu:

In My opinion Apple’s Swift will be in top.Couple of reasons for that

Open source, and apple is keep on improving it.

iOS development is on Swift language

Server side support also there.

with that assumption only i m writing tutorial for Swift. 🙂

Swift language Archives – ProgramTeach

Thanks,

Venkat

http://programteach.com/

like us ProgramTeach

Which programming language will be in great demand in the future?