close
AlliOSSwiftTutorial

Learn Swift 3 – Lecture 1: Getting Started with Swift

learn-swift-3

To learn about swift this lecture 1  is all about swift, what is swift and what are other new features etc. You’ll also learn the basics of swift and you’ll start coding right away in playground. The best way to learn a language is to create a project in it. In this series we will also start a project and take tit to the app store.

Before going into the theory there is one question you should as that, Why I should learn swift when I have very good command on Objective-C? The answer to is is very simple as Apple said “Swift is the future of Apple software development”. There you have it the whole and the only reason why you should learn swift. This first lecture is the base, meaning when we will start the project part we will refer back to this lecture for basics like what was the syntax of do-while loop etc. So there is no need to memorize them all right away as you work with them you’ll get to know the syntax.

This lecture series is based on the official Swift 3 book by Apple. You can download it to your iBooks by clicking here. These lecture series are the simplified version of this book but the app we will be building in this series are our own.

About Swift

Some things to remember for swift are:

  • Swift is a new programming language for iOS, macOS, watchOS, and tvOS apps.
  • Swift has simplified memory management with Automatic Reference Counting (ARC).
  • Swift feels familiar to Objective-C developers and is friendly to new programmers.
  • Playgrounds, an innovative feature that allows programmers to experiment with Swift code and see the results immediately, without the overhead of building and running an app.

A Swift Tour

In swift if you want to print hello world you’ll just do:

and it’ll print Hello, world! as output and without semicolon (;) and it’ll print in console. If you are coming from objective-c it’s kinda similar to what NSLog is doing.

Creating Playground

First let’s create a new playground where we can play with the simple coding snippets of Swift.

create new playground in xcode

Name your playground and select iOS as platform:

add name to create new playground in xcode

After saving you will see your playground window as:

playground in swift for ios

Simple Values

Use let to make a constant and var to make a variable. The value of a constant doesn’t need to be known at compile time, but you must assign it a value exactly once. This means you can use constants to name a value that you determine once but use in many places. For example you can make array with constant values like an array for picker view etc. Copy or write the code below into your playground:

In the example above, the compiler infers that myVariable is an integer because its initial value is an integer. If the initial value doesn’t provide enough information (or if there is no initial value), specify the type by writing it after the variable, separated by a colon. In the example below the Float = 4 will output 4.0:

let implicitDouble = 70.0 let explicitDouble: Double = 70 let explicitFloat: Float = 4

In easy words implicitly means directly and explicitly means indirectly.

Values can never be directly converted to another type. If you need to convert a value to a different type, you need to make an instance of the desired type.

If you remove the string you’ll get an error to something like string + int is not possible. But there is a simpler way to do this by add value in (these) followed by a backslash, so in short this format \() is used. Here is an example:

The last line will output:

inline output of playgrounds by swift

Array & Dictionary:

You can create Array or Dictionary by using standard [brackets], and you can access their elements by index or key in brackets. The values should be comma separated.

For dictionary we will follow the standard format which is Key:Value

But if you need to create an empty array or dictionary you should:

As you can see above that we have initialize the array as a strings array and dictionary as key should be a string and it’s value should be float. If type information can be inferred, you can write an empty array as [] and an empty dictionary as [:], for example, when you set a new value for a variable or pass an argument to a function.

Conditions & Loops:

For Loop:

Swift use the same if, switch, for, while and other control flows as other languages. You just need to understand the syntax and here is an example of for loop in swift which is pretty straight forward:

So this is a for-in loop but if you like the old school for (i:i<10:i++) sort of thing in swift here is how you do it.

You can keep an index in a loop by using ..< to make a range of indexes. Use ..< will execute the for loop 4 times meaning 0-1-2-3, but if you use  it’ll execute for loop 5 times meaning 0-1-2-3-4.

If Condition:

In swift if condition must be a boolean expression which means if you write if score {…} it’ll give an error.

You can use if and let together to work with values that might be missing. These values are represented as optionals. An optional value either contains a value or contains nil to indicate that a value is missing. Write a question mark (?) after the type of a value to mark the value as optional.

If you change John Appleseed to nil in the example below it’ll not run if condition.

If the optional value is nil, the conditional is false and the code in braces is skipped. Otherwise, the optional value is unwrapped and assigned to the constant after let, which makes the unwrapped value available inside the block of code.

Another way to handle optional values is to provide a default value using the ?? operator. If the optional value is missing, the default value is used instead.

Switch Statement:

Switch statements in swift support any kind of data and many comparison operations. To understand switch lets take this example:

There are three cases in this switch statement:

  1. If vegetable is celery
  2. If vegetable is cucumber or watercress. In both cases if one is true it’ll execute the case
  3. Notice how let is used to match the pattern of vegetable. In the above example this block will execute because that’s the only true condition.

At every step try copying the code to the playground we made to see the output yourself and play with it by changing values and see what you get. Let do an experiment by removing the default from this example. It’ll give you an error as default is a compulsory part of switch statement specially in swift.

Another thing which you might have noticed in swift version of switch statement is that there is no break statement. In swift when a case becomes true the program executes the code inside it’s block and exit the switch statement that is why we don’t write break.

Dictionary:

As you know dictionary has the structure as key : value so in swift it’s the same. Next if you are coming from objective c you might have used for-in and in swift it’s also the same.

The line commented in the above example tells you how to init dictionary. Then after that we have initialize two variables one is of type int and other is of type string.

The for-in loop here is getting two values kind and numbers where kind is the key and numbers is the value. It’ll be read as for key, value in dictionary_name notice it’s a nested for-in as there is another for-in which runs for the numbers. This is exactly the same how nested loops work as values are like array and for one key there are multiple numbers so first for is picking up the key and numbers and the second for is picking one number from numbers and then it is checking if the number is greater than largest. If this condition is true then set chosenKind to kind and largest to number and at the last we are printing them both.

Array:

Array is simple in swift. Here is the syntax:

While and Do While Loop:

Use while to repeat a block of code until a condition changes. The condition of a loop can be at the end instead, ensuring that the loop is run at least once which makes it a do while loop. Lets take an example:

While loop is pretty straight forward. While the condition is true keep running the block. In the do-while block do is replaced with repeat but it’ll do the same thing which is execute the code at least once and then read the condition. If the condition is true repeat the block again till it get false.

Methods/Functions:

There is lot we can do with functions in swift. There are many complex ways which are made very easy to do in swift.

Use func to declare a function. Call a function by following its name with a list of arguments in parentheses (…). Use -> for function’s return type.

There is a cleaner way of calling function. You don’t need to write the names of parameters, you can simply give it values. This is called as no argument label.

To make it we write _ before the name of parameter. Here is an example:

So you see I haven’t added _ to person so I need to write it as Person: “John” but for lucky number I just wrote 3 and swift gets it that this is luckyNum: Int. The out put I’m seeing on playground is

“Lucky Number 3, for John.”

Go ahead and make both arguments as no argument label as an experiment.

You can also make a function that returns multiple values. In the example below we are giving an array of scores to the function and it is calculating min, max, sum for the John.

So we have given multiple -> return types as you can see. When we are returning we are using comma separation to return the multiple values. The for loop score in scores you might have noticed that score has no datatype, but it get the data type of scores that’s magical in swift.

To call and print the values we get from this method:

So you see we can do this by putting (dot) and either by name or by index.

You can also add variable number of arguments.

It’s like collecting them in array.

Nested Functions:

Nested functions have access to variables that were declared in the outer function. Best practice to use nested functions to organize the code in a function that is long or complex.

Functions can return another function as its value.

To remember this syntax just see the return type and argument of addOne which is simple one. So to write of for makeIncrementer just use (Int)->Int which is the argument and return type of addOne and you us it as return type of makeIncrementer.

A function can take another function as one of its arguments.

Argument condition is taking (Int)->Bool so any method with this argument and return type is valid.

Closures:

In objective-c closures are called blocks. Difference between block (Objective C) and closure (Swift) has very slight. You might have seen some functions in objective-c that have a cap sign (^) this is a block. For more information on Blocks see this example by Apple. In nested functions the example we did is also a type of closure.

You can write a closure without a name by surrounding code with braces ({}). Use in to separate the arguments and return type from the body.

Don’t worry if anything seems difficult. Leave a section, because you’ll learn it as you program the apps. You just need to go through the syntax at least once.

Objects and Classes

Use class followed by the class’s name to create a class.

Create an instance of a class by putting parentheses after the class name. Use dot syntax to access the properties and methods of the instance.

As we know in OOP there is a default constructor which is an initializer to set up the class when an instance is created. We do it with init in objective-c and we are going to do the same with swift.

See how I’ve used self.name to access variable of same class. It is also use to distinguish between class variable and argument variable. You can use deinit to create a de-initializer if you need to perform some cleanup before the object is deallocated.

Inheritance or Subclass:

Subclasses (Child Class) include their superclass (Parent Class) name after their class name, separated by a colon. There is no requirement for classes to subclass any standard root class, so you can include or omit a superclass as needed.

If there is a method in subclass (Child Class) that override the superclass (Parent class) should be marked with override. If you don’t do this will throw compiler error.

Using the NamedShape class above as parent and creating a Square child class.

First compare the use of self.sideLength with self.name in the previous code snippet.

In this code snippet above we have the init method of Square class. There there is a class function and after that we override the func of parent class. Also there is a super.init of superclass (parent class).

Getter & Setter:

This is a lecture series. It will be updated on daily basis. This section will update soon.

Tags : learn swiftswiftswift basics
Chaudhary Talha

The author Chaudhary Talha

I'm an iOS developer by profession and UI/UX designer by passion. All my tutorials are based on my personal experiences and whenever I learn something new I share it with the world.
x
Like what we are doing? Join Us! Become a contributor at iOS Pakistan.