Swift 3: Beyond the first look


I am using Apple Swift version 3.0.2 (swiftlang-800.0.63 clang-800.0.42.1)

How do I know which Swift version I am using?
Run the command in Terminal,

xcrun swift -version

Swift is a type-safe language. It infers data types from default value provided for variable/constant.


Each variable need an initial value OR have to be declared with a type.

var aStringVariable = "Hello world"
var anotherStringVariable: String
var anIntVariable: Int                  // 64-bit signed integer
var anInt8Variable: Int8                // 8-bit signed integer
var anInt16Variable: Int16              // 16-bit signed integer
var anInt32Variable: Int32              // 32-bit signed integer
var anInt64Variable: Int64              // 64-bit signed integer
var anUnsignedIntVariable: UInt         // 64-bit unsigned integer
var anUnsignedInt8Variable: UInt8       // 8-bit unsigned integer
var anUnsignedInt16Variable: UInt16     // 16-bit unsigned integer
var anUnsignedInt32Variable: UInt32     // 32-bit unsigned integer
var anUnsignedInt64Variable: UInt64     // 64-bit unsigned integer
var aDoubleVariable: Double
var aFloatVariable: Float
var aBooleanVariable: Bool
var aCharacterVariable: Character

Character can be double quoted in Swift. If not defined explicitly, it will be inferred as String

var myChar : Character = "a"

In general, there is no syntactical differences between Float and Double, but when you print the values you will get higher precision in Double. But, Double isn’t always better — in cases where speed is more important than accuracy, you might want to choose Float instead.

var pi: Float = 3.14159265359
var pi2: Double = 3.14159265359


/* Output


Constant starts with ‘let’ keyword in Swift. Constant value can be set after the declaration, but only once.

let aConstant = 32
let anotherConstant: Int
anotherConstant = 64

Using ‘let’ is highly recommended whenever possible. Besides type safety there are some internal performance optimization by Swift compiler.

Literal vs Constants
A literal is a value that is written exactly as it’s meant to be interpreted. In contrast, a variable is a name that can represent different values during the execution of the program. And a constant is a name that represents the same value throughout a program. But a literal is not a name — it is the value itself.


let aString = String() 

Print all the characters in a String

var anotherString = "Hello"
for character in anotherString.characters {
    print (character)

Notice that String doesn’t have any length property

let aString = "Hello World"

Reverse a String

var simpleString = "Hola"
var reversedString = simpleString.characters.reversed()
// Here, reversedString is a ReversedCollection<String.CharacterView>
// So you can not just write print(reversedString). Instead,

for character in reversedString {
    print (character)

Conditional statement basics

  • Curly braces are REQUIRED, even if there is a single statement.
  • Parenthesis are not needed around the condition.
  • Pre-increment/decrement is deprecated and will be removed in Swift 3. (Post-increment/decrement too)

If-else condition

let x = 5

if x < 5 {
    print("x < 5") } else if x == 5 {     print("x == 5") } else {     print ("x >= 5")

While loop

var index = 0
let x = 5

while index < x {
    index += 1      // index++ is deprecated

For loop

for i in 0 ... 10 { // for (var i = 0; i <= 10; i++ )
    print("i = \(i)")

for i in 0 ..< 10 { // for (var i = 0; i < 10; i++ )
    print("i = \(i) and i * i = \(i * i)")

Do while loop

var index = 0
let x = 5

repeat {
    index += 1
} while index < x

Optional basics

  • Variable/constant has to be intialized before used. Otherwise it will produce compile error
  • Optional variable/constant can have a value or it will be ‘nil’, no exception
  • Optional variable/constant is strongly typed too. Either contain a valid value or ‘nil’
  • Opitonal variable/constant can be set to ‘nil’ explicitely
  • Optional variable/constant need to be unwrapped before use. Before unwrap you need to be sure it has a value.
var optionalString: String?
var optionalInt: Int?

if optionalInt != nil {
    var anIntVariable = optionalInt! // unwrapping
    print (anIntVariable)

// OR

if let anIntVariable = optionalInt {
    // execution will be here iff optinalInt != nil
    print(anIntVariable) // by default unwrapped
} else {
    print("optionalInt is nil")

String format

let a = 5
let b = "World"
let c = 3.6

print("Hello \(a) and \(b) but \(c)")

Function basics

  • Function params are by default constant.
  • On calling a function, you need to specify the name of all variable as key:value (except the first one)
func foo() {
    // no params, no return type

func boo() -> String {
    return ""
    // no params, String return type

func coo(first: String) -> String {
    return first
    // one String param, String return type

func doo(first: String, second: Int) -> Int {
    return second
    // one String param, one Int param, Int return type

func moo(first: String, second: Int, third: Int = 2) -> Int {
    return third
    // Default param third set to 2

func koo(first: String) {
    // first = "Haha" // Error: params are constant
    // var first: String will make it a varaible

doo("Haha", second: 5) // Error: doo("Haha, 5)
moo("Haha", second: 5) // omit the default param
moo("Haha", second: 5, third: 3) // default param value


  • Instance variable need to initialized with default value OR the class need to have a constructor
  • Constructor is a special function with name ‘init’
  • Current instance reference is ‘self’
class Person {
    var firstName: String = "Sherlock"
    var lastName: String = "Holms"
    var age: Int

    init() {
        // Constructor
        self.age = 50

    // Method
    func getDescription() -> String {
        return "FirstName: \(self.firstName) and LastName: \(self.lastName) and Age: \(self.age)"

var p = Person()    // Creating object
print("FirstName: \(p.firstName)")

instanceof OR is of type

class Person {
    var firstName: String = "Sherlock"
    var lastName: String = "Holms"

class Student: Person {
    var id: String = "0123456789"

var s = Student()

if s is Person {
    print("s is a Person too")

    var p = s as Person // casting to Person

} else {
    print ("This will not be executed")

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s