In Part 1 of The Swifty Way ! – Introduction to Swift Programming we started by praising Tuple(data type introduce in swift) and we discussed the concept of var, let , optional , class ,structs and at last about initializers. Now in this blog lets start our exploration by looking into the reason that makes Tuple praiseworthy and after which we will look into other swift language features.
Tuples
Swift classify types into two different kinds the named types and the compound types. Tuple is a compound type. Compound types are types without a name.
We can define tuple as a group of comma separated data types(different datatypes) enclosed within a () which act as a single type.
While using tuple we can make the our program more readable using typealias as shown in code below.
typealias DoubleIntTuple = (Int,Int)
var testDubleIntTuple:DoubleIntTuple = (10,20)
typealias provide an alternative name to represent the tuple (Int,Int).
The example that strikes mind of a developer is the scenario when a network call back is received from backend system. For http request made the main components that we would have interest in are the http response code and a description. The following show how we can represent these two using a tuple
(400, “Bad Request”)//HTTP CODE 400 and its description
(401, “Unauthorized”)//HTTP CODE 401 and its description
Accessing value from tuple
The code below shows how to access the different value from tuple.
let (status,description) = (400, “Bad Request”)//HTTP CODE 400 and its description
print(description + “with status \(status)”)
If we require only a specific type from tuple we can use the “_” to ignore the unwanted values as show below.
let (_,descriptionOnly) = (400, “Bad Request”)//HTTP CODE 400 and its description
print(descriptionOnly)
The above shown is one among the multiple ways to access the values from tuple.
Control Flow Statement
Lets look in to the observable changes that came in to control flow statements in swift while comparing with the normal c style statements supported as in Objective C. Normal c style for loop is deprecated and compilee will show a warning if we try to use that.
There are no more do-while statement instead we use repeat-while which works as the replacement for do-while. When you get closer to swift you will definitely understand why the introduction of repeat-while as a replacement for do while was a necessity.
The following code is example for implementation of for, repeat-while and while statements
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
//for Loops for count in 0...10{ print("hello") } //while loop var condition = true; var count = 0 while(condition == true){ print("hello") if (count == 10){ condition = false; } count = count + 1 } //repeat- while loop condition = true; count = 0 repeat{ print("hello") if (count == 10){ condition = false; } count = count + 1 }while(condition == true) |
In case of “for” loop you might have notice the rage is specified after the “in” keyword.
0…10 represent 0 to 10 including 10
0..<10 represent 0 to 10 excluding 10
Switch :
Now lets explore the Switch statement in swift.
Switch cases support a value,which can be a string, a character, a value of any integer or floating-point type, tuple. Unlike Objective C it does not fallthrough by default and does not mandate the break keyword after each case. An empty case would give a compile time error and if you want to ignore a particular case break can be used.
The following is a simple example for Switch statement
1 2 3 4 5 6 7 8 9 10 11 12 |
var value:String = "" switch(value){ case "Case 1": print("case 1") case "Case 2": print("case 2") case "Case 3": print("case 3") default: break } |
In swift the switch case must be exhaustive, ie., all the cases that a switch case would encounter need to be considered and implemented inside the switch or else compiler would throw an error. In the above example the default implementation makes switch exhaustive.
Optional binding, ?? operator , guard keyword
In our Part 1 of this series we talked about optional and its unwrapping, Optional binding and usage of guard keyword is another way to access the value from an optional type.
Let look into optional binding and the following code show the same
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
var someOptionalValue:String? = nil someOptionalValue = "Hello " if let value = someOptionalValue{ print(value) } someOptionalValue = nil if let value = someOptionalValue{ print(value) }else{ print("the value is nil") } |
In the above code we can see that we have used if-let syntax and the value of the string variable someOptionalValue have been accessed and assigned to the “value” literal . Inside the if-let block the “value ” literal could be used instead of “someOptionalValue” literal. If the someOptionalValue is nil then the if-let block will not be executed and in this case we can use an else block if required.
Please note that the above code, using if-let syntax, does the function of nil check using if statement and unwraps optional value at the same time and the only shortcoming of using this would seem to be the scope of the unwrapped variable to be restricted inside the if-let block.
Usage of guard keyword could come handy in cases when the scope of the unwrapped value need to be prevented from being constraint as similar to the case of using if-let syntax. The following code show the usage of guard statement
guard let unwrappedValue = someOptionalValue else{
return;
}
print(unwrappedValue)
The guard statement is similar to the usage of if-let syntax and the difference being the fact that the scope the unwrapped literal is extended outside .
The behavior while using guard statement is that the else block us mandatory and guard statement will not fallthrough if the condition is not met. Thus the else statement used along with guard will require “return” from the function block being used.
Now that we have reached the concluding section and before we conclude the part 2 we would look into one more topic Nil Coalescing Operator (??).
var someOptionalValue:String? = nil
var unwrappedValue = someOptionalValue ?? “default string”
The equivalent expression for this would explain more
var uunwrappedValue = (someOptionalValue != nil ? someOptionalValue! : “default string”)
Thus the “??” operator is the short hand syntax which would check if the optional value is nil and if found nil returns a default value similar to “default string” in the above case and the other case if the optional is not nil then the optional is unwrapped and retunrs the unwrapped value
Now it’s time to mark the end of the two part introductory blog series for swift language exploration.
Hoping this blog series has become a head start for introducing you to a new world of programming the Swift.
Leave a Reply