Free Shipping

Secure Payment

easy returns

24/7 support

  • Home
  • Blog
  • Beginner’s Guide to Swift Programming – Part 1

Beginner’s Guide to Swift Programming – Part 1

 July 9  | 0 Comments

To those technology enthusiasts who are starting the exploration of the language swift, this write up would be a head start.

The normal convention to start every programming language by writing a Hello World !. However in our case lets start by praising one of the wonderful datatype the Tuple that makes the multiple return possible in swift functions.

A developer who has worked in swift would describe swift as a strongly typed, type safe language that is designed with the capability of interoperability with the existing Objective C code and also having full access to the Objective C API within swift.

Sound great right, ok now lets explore little more specifics of the swift language:

Concept of VAR and LET

The var and let keyword is to define mutable and immutable types. Use var keyword before a variable and let keyword before a constant value.
If let keyword is used to create a constant, one can only assign a value to it exactly once. It is not necessary to know the value of a constant at compile time.

//Syntax
let myConstant = 52

myConstant = 74 //This line will produce compilation error

//var and let example
let myExampleConstant = 52
var myExampleVariable = 52

In the above example you would wonder the type of the variable not mentioned. Type inference capability of swift compile does the job for us. myExampleVariable would be inferred as Int type.

The following declaration shows how we explicitly define the type of the variable.

var myExampleVariableWithType:Int = 52

The Optional type

The situation when there is no value for a variable in swift is handled via the concept of Optional. By marking a variable as Optional we define a variable wherein the variable can have value or the variable doesn’t have a value at all.

A variable defined as a ‘var’ or a ‘let’ in previous section are all non optional type, ie., these type will never be having nil value in their lifetime.

Let have a look into some swift code that which is used to define optional

var someOptionalIntValue:Int?
var someOptionalStringValue:String!

The above two variable are marked optional. The “?”(question mark) or the “!”(exclamation) at the end of the type would mark a value to be an optional.

Difference between the ? and ! is best understood by getting to know about unwrapping process.

The value of the optional marked with “?”(question mark) cannot be directly used. The situation of a value marked as optional can be compared to an item stored inside a container and in order to use this item we need to open the container.

However in the second case in which the optionals marked with “!”(exclamation) are the ones that are called explicitly unwrapped optional. Unlike the optional marked with “?” the value of these optional can be directly accessed. One need to be vigilant while using “!”, as in the case when the optional value is nil and if developer access the value, a runtime error will occur.

If we try to assign a nil to a non-optional value a compile time error will be generated. The following code demonstrates the same.
var myExampleVariable = 52
myExampleVariable = nil //INVALID This line will show compilation error stating that Nil cannot be assigned to type Int (playground xcode 7.3)

The above situation cane be handled by using optional value.
var someOptionalDoubleValue:Double? = 52
someOptionalDoubleValue = nil; // Assigning nil to an optional value is valid

In the case when a optional value is assigned to a non-optional type then the optional value need to be unwarapped.
By now you might have noticed that none of the optional values are declared with the “let” type in above examples.
What do you think will there be a case that would lead a developer to declare optional let type that which is immutable ? Think about it!

Unwrapping the Optionals

Unwrapping is process of accessing the value from an optional type. The following code will give us a notion on the unwrapping process of optional values.

a. Declaring a optional variable
var someOptionalStringValueWithQuestionMark:String?

b. Assigning a value to the variable
someOptionalStringValueWithQuestionMark = “hello world”

c. Printing the variable
print(someOptionalStringValueWithQuestionMark) // Optional(“hello world”) will be the out put

d. Using the “!”(exclamation) operator(also know as bang operator in the current context) at the end of variable to access the value from the variable(The unwrapping of optional variable happens)

print(someOptionalStringValueWithQuestionMark!) // hello world will be the out put here

e. Assigning nil value and trying to unwrap and print the value

someOptionalStringValueWithQuestionMark = nil
print(someOptionalStringValueWithQuestionMark!) // This line will produce a runtime error

The reason for the crash is obvious in this case and by now the reason for the runtime error might have struck your mind.

However for implicitly unwrapped optional the unwrapping is not necessary and incase we use the bang operator here the value of the variable will still be returned. The following code is an example for the same

a. Declaring a implicitly unwrapped variable

var someOptionalStringValueInplicitlyUnwrapped:String!

b. Assigning a value to the variable

someOptionalStringValueInplicitlyUnwrapped = “hello world”

c. Printing the variable

print(someOptionalStringValueInplicitlyUnwrapped) // “hello world” will be the out put

d. Use bang operator also will give the “hello world” as output

print(someOptionalStringValueWithQuestionMark!)

Class and Structs

The only difference between the two is that classes are reference type and structs are value type.

While a struct object instance is used the value is copied and this behavior can be noticed in the example shown below. The struct object instances aPoint, bPoint and cPoint are all having different value and is not mutated while it is assigned, passed to a function parameter or returned from a function.

Where as in case of the class object instance being reference type all the variable holding the same reference gets mutated and the behavior is noticed with all the three variable aPoint, bPoint and cPoint.
Classes and structs can have methods. The getAnAribitararyPoint is an example of the method.
The following shows how the class and struct could be declared.

Class sample

/* Class declaration start */
class SomeArbitraryPoint{
var xArbitrary:Int = 0;
var yArbitrary:Int = 0;
func getAnAribitararyPoint(var aPoint:SomeArbitraryPoint) -> SomeArbitraryPoint {
aPoint.xArbitrary = 3
return aPoint
}
}
/* Class declaration end */
var aPoint = SomeArbitraryPoint()
aPoint.xArbitrary = 1
aPoint.yArbitrary = 1
var bPoint = aPoint
bPoint.xArbitrary = 2
bPoint.yArbitrary = 2
var cPoint = aPoint.getAnAribitararyPoint(bPoint)
print("Value of aPoint.xArbitrary \(aPoint.xArbitrary)")//Output of the print Value of aPoint.xArbitrary 3\n
print("Value of aPoint.yArbitrary \(aPoint.yArbitrary)")//Output of the print Value of aPoint.yArbitrary 2\n
print("Value of bPoint.xArbitrary \(bPoint.xArbitrary)")//Output of the print Value of bPoint.xArbitrary 3\n
print("Value of bPoint.yArbitrary \(bPoint.yArbitrary)")//Output of the print Value of bPoint.yArbitrary 2\n
print("Value of cPoint.xArbitrary \(cPoint.xArbitrary)")//Output of the print Value of cPoint.xArbitrary 3\n
print("Value of cPoint.yArbitrary \(cPoint.yArbitrary)")//Output of the print Value of cPoint.yArbitrary 2\n

Struct Sample

/* Struct declaration start */
struct SomeArbitraryPoint{
var xArbitrary:Int = 0;
var yArbitrary:Int = 0;
func getAnAribitararyPoint(var aPoint:SomeArbitraryPoint) -> SomeArbitraryPoint {
aPoint.xArbitrary = 3
return aPoint
}
}
/* Struct declaration start */
var aPoint = SomeArbitraryPoint()
aPoint.xArbitrary = 1
aPoint.yArbitrary = 1
var bPoint = aPoint
bPoint.xArbitrary = 2
bPoint.yArbitrary = 2
var cPoint = aPoint.getAnAribitararyPoint(bPoint)
print("Value of aPoint.xArbitrary \(aPoint.xArbitrary)")//Output of the print Value of aPoint.xArbitrary 1\n"
print("Value of aPoint.yArbitrary \(aPoint.yArbitrary)")//Output of the print Value of aPoint.yArbitrary 1\n
print("Value of bPoint.xArbitrary \(bPoint.xArbitrary)")//Output of the print Value of bPoint.xArbitrary 2\n
print("Value of bPoint.yArbitrary \(bPoint.yArbitrary)")//Output of the print Value of bPoint.yArbitrary 2\n
print("Value of cPoint.xArbitrary \(cPoint.xArbitrary)")//Output of the print Value of cPoint.xArbitrary 3\n
print("Value of cPoint.yArbitrary \(cPoint.yArbitrary)")//Output of the print Value of cPoint.yArbitrary 2\n

Use of Class, Static, Final keywords before methods

The methods can be marked final with final keyword . It is not possible to override there methods in subclasses.

Methods can be marked as static as well and the behavior of static methods is equivalent to final methods.

Another kind are the class methods. The only difference with the final/static being the fact that overriding the implementation in the subclasses is possible with function marked with class keyword.
Now that its time to conclude this blog . Hope you have enjoyed reading !

Even though we conclude The Swifty Way ! – Introduction to Swift Programming Part 1 here, the cool features of swift does not stop with these. There are lots more !!
Watch this space for more and in The Swifty Way ! – Introduction to Swift Programming Part 2 we will continue our exploration…

Keep visiting our site www.acadgil.com for more updates on IOS and other technologies.

>