Up and Running with Swift Programming

Swift Introduction with Optionals, Functions and Strings

Ashish P
iOSMastery.com

--

In this article you will learn these fundamentals of swift:

  1. Optionals, Optional binding, Force Unwrapping

2. Functions

3. Creating Arrays

4. Creating Dictionaries, iterating operations

5. String Operations

6. Conditionals, Switch statement, if statement

Introducing Swift

Swift is the new programming language developed by apple. If you are an Objective-C programmer Swift will feel familiar to you. It follows the same method names and parameters from Objective-C. It also includes cocoa frameworks from Objective-C. Moreover Swift code can be used along with Objective-C code. Swift code is much more concise, faster to execute and easy to debug. People have been talking about Swift since it is introduced and most of them find it easy to adapt and more expressive. Even objective-c developers with decades of experience find it easy and more intuitive. It is so simple yet powerful that after a while you will feel it to be second nature. Swift is concise, intuitive, and faster to execute. Most importantly it is wildly adopted, there are thousands of repositories on github and you can find solutions for most of your problems on stack-overflow.

Before getting into swift programming, i would like you to know about a great tool that apple introduced just for learning and experimenting with this new language. It is called Playground. It is so great that you won’t have to worry about creating the project or to build your project to compile your code anymore. You can directly experiment with the swift code and see the results immediately. This makes the learning experience more fun. Thats why i recommend you to use playground for trying and tweaking the code immediately. To try to write the code yourself while learning about the concepts is the most important thing while learning the programming. It is what that keeps the fun of creativity, innovation and improvisation alive.

You don’t have to download or install it separately. All you need is Xcode. Once you installed Xcode and open it, you will see the following window

To create a Playground file choose the first option that says Get started with a Playground. You will be taken to this window:

This is where you can name your playground file and choose the platform for iOS or OS X. On clicking next you will be asked to choose the location on your mac to save the project. Choose as per your convenience and click Finish. Now your playground file is ready for you to code.

You will see the following window:

Introduction to playground

This is a normal playground file. Similar to your class in a Xcode project. On the left side you see a variable which holds a string “Hello, Playground”. On the right side you see the result or the value of the variable on that line. You can see the result of any calculation and operations immediately at runtime as shown in the image below:-

Real time output in playground

So why waste any more time ? Lets code!

So lets start with Fundamentals:

Variables

Lets get straight to the point. Here is how you define variable in swift.

var myName:(String) = “Ashish”

Pretty obivious and easy to understand isnt it? Here we define a variable ‘myName’, we do this with var keyword followed by variable name, followed by a colon ‘:’. The colon is followed by the data type which in this case is a String ( String is the new data-type introduced with Swift ). We assign a string value “Ashish” to the variable to initialise.

In Objective-c you would do it as:-

Create a variable in Objectives

In swift we declare any type of variable with keyword ‘var’. var also denotes mutability which I will explain in a bit.

There is no semicolon at the end of the statement. Semicolons are optional in swift.

Constants

Creating variable was piece of cake. Now lets see how do we declare constants. Lets assume if you want the var ‘myName’ to be a constant, you can do it this way:-

Create a Constant in swift

yes everything except the keyword let is same. Keyword ‘let’ in swift stands for immutability. So for any object or value you want to keep as constant, just declare it with keyword ‘let’.

few more examples of constant:-

Specify Data Type in Swift

Swift preferes imutability over mutability so much that in swift 2.0 (Xcode 7), Compiler alerts if your variable is actually a constant and you should replace ‘var’ with ‘let’. This makes code much safer in multitasking environment because it knows what is not going to change.

Type inference in swift

Swift can infer the data type of a variable or a constant. What this means is you don’t have to mention the type explicitly. Consider the following example:-

Type Inference in Swift

here we are not specifying any data-type for the variable ‘myName’, still the code works just fine. The reason for this is swift automatically detects or infer the data-type of the value “Ashish” which is a string.

Similarly,

Type inference for int and float in swift

Swift chooses Double rather than a Float when inferring the type of floating-point numbers.

Note:- You can use any unicode character as a variable or constant name.

for example,

let π = 3.145927

(Press alt + P on your mac to type unicode character ‘π’) .

This type inference makes the swift a type safe language.

String

Swift introduced few new data types, one of them is String. It automatically bridges with NSString and incorporates all its properties. Hence you can use String anywhere you would use an NSString.

for example,

Data Type Conversion in swift

Here we define a String and initialize it with an int. We then converted it to an Integer by using NSString’s intValue property.

To count the characters or length of the string :-

Calculate length of string in swift

you will get the answer as 5.

consider the String below:-

To Access the character at particular index use the properties startIndex , endIndex and functions predecessor( ), successor( ).

Calculate index of character in swift

Access a Character at an index outside of a string’s range will trigger a runtime error.

Accessing index of character outside range of string length

String Interpolation

Using a variable in String

you can also perform operations on values while using them in a string

more String Interpolation

Concatenating a string

Concatenating a string

Inserting and Removing Characters in string

To insert a character into a string at a specified index, use the insert(_:atIndex:) method.

Inserting Character in string
Output:- welcome now equals “wow!”

To insert the contents of another string at a specified index, use the insertContentsOf(_:at:) method.

Insert Content of string in swift
Output:- name = “wow thats great!”

To remove a character from a string at a specified index, use the removeAtIndex(_:) method.

Remove Character in Swift

Output:- welcome now equals “wow thats great”

Read more about String here

Functions

Following functions takes three parameters firstName, lastName and a space between them and returns the string after joining them

Function Syntax Swift

Changing value of s1 is not allowed because parameters are of type let even if we pass variable type parameters to the function.

To make s1 mutable declare s1 as var.

This is how we make the parameters of a function mutable

Calling the function

Function call swift

here we pass the firstName, lastName and the joiner String and assign the result to a new variable ‘name’

This illustrates simple and clear syntax of swift.

Optionals

Swift introduced a lot of great features one of them is optional. An optional is used where a value may exist or not. This concept doesn’t exist in C or Objective-C. In objective-c if a function returns the absence of an object it would return nil. So we need to handle this case, with something like

if (object != nil ) or if (object) . But this doesn’t work with structures or enumerations where in case of absence of value we will get NSNotFound.

In swift we have a single type optional which can handle any data-type if it is absent or present.

An Optional can be declared by putting a ‘?’ mark after data-type of a variable.

Optional Declaration

where name is an ‘optional’ where a value of name could be nil. Infact if we don’t initialize the name variable with a value, it is automatically set to nil.

If an Optional has a value that means it is not nil.

Force Unwrapping

To get the optional we can do it like:-

Force Unwrapping in Swift

This is like telling the compiler that I know theres a value in the variable ,give me the value. Force unwrapping a variable which contains a nil value will produce a runtime error.

Optional Binding

To handle the nil case, create a temporary constant or variable and assign it the optional. Then check if the const contains the value i.e. not nil.

The above declaration and ‘if’ condition can be combined as follows :-

Optional Binding

This condition checks if an optional contains a value, only then it executes the code in the block. If value exists then ‘name’ is assigned to ‘aStr’. This is called as optional binding.

Learn more about optionals here

Conditional Statements in swift

Swift made a few syntactical changes with conditional statements to make it easier to use.

Lets consider an if statement

If Statement.swift

For Loop

//iterating over an array in swift

Dictionary in Swift

Creating a dictionary

Creating a Dictionary in swift

Iterating over a dictionary

Output:- “[Ashish, Akash, Prakash]\n”

Switch Statement

Switch statement in swift supports checking against any type of value. Switch can now validate the implemented cases against any conditions unlike objective-C where it can only compare against equality.

Switch Statement.swift

Switch can compare between range

try changing the number value below to test the cases

Switch Range compare

Switch can used to compare Tuple.

Try changing the values of the tuple to test the cases

Switch Tuple Compare in swift

Value binding with Switch

Switch can assign values to temporary variables or constants which can then be used to create complex conditional statements to evaluate. This assignment is called as value binding.

Value binding in swift

Thus you can see that switch has evolved a lot in swift. I am sure you will find it a lot more useful than objective-c. You can share in the comments below, any use cases where you think using switch makes a good sense. You are always welcome to share any code related to the topic if it can explain the concepts more.

If you liked my post you can check my other posts on swift here. You can check my blog www.onestopsios.com. See you again happy coding !

--

--