[archive]

Welcome on my first part of tutorials about the programming language Swift. In this very first tutorial we will focus on types, operators and collections that are available in Swift. We will use currently newest Swift 2.1 version with Xcode 7.1. To be able to run the code snippets that will be written further, you will need Xcode 7.1+ with Swift 2.1 compiler.

NOTE:

This tutorial is not intended for a very beginners. It’s intended for people that know about programming and have some experience in the programming concepts already.

Declarations and Types

When you want to define a variable in Swift you do it like that:

var myInteger = 10

as you can see, there is no typing information. That’s because Swift can infer the type from the assigned value, which is here an integer. So it will be an implicit typing to:

var myInteger: Int = 10

You can also declare the variable only and later assign a value to it. Swift will check, if you are using an uninitialised variable, so it will be a hard compiler error.

var myInteger: Int

...
myInteger = 10

Another type of variable here is a constant. You define a constant with a let keyword. If you type a variable with var you can change the value later, if let you can’t.

let stringConstant =  "Hello World! :)"

as well as the variable, you can declare a constant and assign a value for it later, but only for once. Once initialised, you can’t change it’s value. However, it’s a good practise to assign the value for constant in the declaration.

Basic Types

In Swift there are some basic types that looks and works like basic C types, but with the difference here that they are actually first class objects.

Bool
String
Double
Float
UInt
Int

They have methods that you can use, you can extend them if you want to and they have properties like min and max. In addition to Swift types, you have access to other types when you will import the Foundation library.

Int8, Int16, Int32, Int64
UInt8, UInt16, UInt32, UInt64
UTF8, UTF16, UTF32, UTF64
Float80

Also, Swift supports a type aliasing, so you are able to define your own type that maybe more appropriate or more understandable in your source code

typealias Unsigned = UInt64

Another thing worth to mention here is the fact that Swift does not support implicit type conversion. Below is an example:

var myInteger: Int = 10
var myDouble: Double = 10.0

var result = myInteger + myDouble // this will result with a hard compiler error

// instead above you should perform:
var result = myInteger + Int(myDouble)

The result variable will be of Int type.

String Type

In Swift you can use both String type and the NSString type. To use NSString you have to import the Foundation library

import Foundation

let myString: String = "Hello"
let myNSString: NSString = "World!"

The difference in those two types are that the String type is bridged to the NSString type. String type is a kind of a subclass of the NSString. You will be able to assign a String to the NSString but you won’t be able to it the other way. However, you can assign a NSString instance to the String variable, but you need to do an explicit casting like this:

import Foundation

let myString: String = "Hello"
let myNSString: NSString = " World!"
let castedString: String = myNSString as String
let concatenatedString = myString + castedString // "Hello World!"

Becasue the String is an object type, you can perform many operations on strings like below:

let myString: String = "Hello World! How Are you?"
myString.hasSuffix("you?") // will return true, if the string ends with "you?" string
myString.hasPrefix("Hello") // will return true, if the string begins with "Hello" string
myString.characters.count // will return the number of used characters

there is a lot of methods to use and compare strings. One more thing about the string is that you can compare strings by ==, <=, >=, <, > operators, for example:

let myString: String = "Hello World! How Are you?"
let myShortString: String = "I am fine :)"

myString > myShortString // this will return true
"100" < "101" // will also return true :)

More details at https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/StringsAndCharacters.html

Optionals

There are some situations when you are not sure, if your method is going to produce any value as a return value. It may return nothing, because the input value was bad, or there was some internal computation error that was not handled properly. In Swift you have a special type for that kind of situations – optionals! You define the optional type with providing the ? mark. Let’s look at the example below:

var optionalInt: Int?			// implicit: var optionalInt: Int? = nil
let stringValue: String = "13"
optionalInt = Int(stringValue)            // Optional as the return value

if let value = optionalInt {               // safely unwrap the optional value
    print("String converted to: \(value)")    // this will print "String converted to: 13"
}

// you can also check it like this 
if optionalInt != nil { // check if there is a valid value
    print("String converted to: \(optionalInt!)")  // unwrap the value explicitly (force unwrapping), this will print "String converted to: 13"
}

We assigned an optional return value from method Int() to the optionalInt variable. The Int() method could return an optional that is empty inside, it has no value. Still, it’s a valid object but without a value inside of it.

Force unwrapping

if let statement checks what is the inside the optional variable, if there is a value it enters the inside body, if not nothing bad happens and the code from the if body is not executed. If you would like to try unwrap the value from the optional you can with using the ! mark, as below:

var optionalInt: Int?
let stringValue: String = "13"
optionalInt = Int(stringValue)            // Optional as the return value
print("String converted to: \(optionalInt!)") //this will print "String converted to: 13"

But what if the optionalValue was empty? What would happen? It would crash spectacularly, resulting with the app crash. You cannot unwrap the value explicitly unless you are pretty sure that there is a valid value, not nil. However, it’s a good practise to perform checks like the one above (especially by the if let clause), as it results with higher code quality, security and of course stability.

Thank you for reading, that’s all for Today. There will be more in next days :) I have attached a playground file for this topic here: types_operators_collections.playground