The code structure
Before starting to write Swift, you have to be aware of its structure, as it is a very important thing to know in any programming language.
As we said earlier, Swift is not a superset of C. For sure it's influenced by C and Objective-C but easier and fun to use than both.
I will share with you a piece of code in Swift to show its structure:
import UIKit let pi = 3.14 //Display all even numbers from 0 to 10 for i in 0...10 { if i % 2 == 0 { println("\(i) is even") } } func sayHello(name: String = "there") { println("Hello \(name)") } sayHello(name: "John") // will print "Hello John" sayHello() //Will print "Hello there", based on default value
Tip
Downloading the example code
You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed direct to you.
If you check this code, you will find that we don't use semicolons. This is because in Swift they are optional. However, compiler will not complain if you do use them. The only area where semicolons are required is when you write multiple statements in the same line.
In Swift, you use var
for variables, and let
for constants; but this doesn't mean that Swift is not a typed language. The compiler, based on the initial value, identifies the type implicitly. But in some cases, you have to write the type if you don't set an initial value; or the initial value is not sufficient to identify the type.
Consider the following code for example:
var count = 5 var msg : String var total : Double = 0
In this code, the count
variable is of the Int
type, because its initial value is in integer. In the msg
variable, we didn't set an initial value, so we will have to explicitly write the type of the msg
variable. The same is applicable for total
; we need it to be of the Double
type but as its initial value is not sufficient, the compiler will consider it as Int
.
In Swift, you will see that there is no main function to start with, as the code written in the global scope is considered as the start of your program. So, you can imagine that a single line of code in Swift can be considered as a program!
The last thing I want to mention is that curly braces are very important in Swift, as they are mandatory in any control flow statements, such as if, while, and so on.