Swift Introduction

by "Blag" - Senior Developer Evangelist

Return to Geeky Thursday

What is Swift?


Swift is a general-purpose, multi-paradigm, compiled programming language.

Protocol-oriented, object-oriented, funcional, imperative and block structured.

Borrows ideas from Objective-C, Rust, Haskell, Ruby, Python and many more...

Swift was developerd by Apple.

Open Source and available on Linux.

How to install Swift?


If you're using Linux


wget https://swift.org/builds/ubuntu1404/swift-2.2-SNAPSHOT-2015-12-18-a/swift-2.2-SNAPSHOT-2015-12-18-a-ubuntu14.04.tar.gz


tar -zxvf swift-2.2-SNAPSHOT-2015-12-18-a-ubuntu14.04.tar.gz


export PATH=/path/to/swift-2.2-SNAPSHOT-2015-12-18-a-ubuntu14.04/usr/bin/:"${PATH}"


sudo apt-get install git cmake ninja-build clang 

     uuid-dev libicu-dev icu-devtools libbsd-dev 
     
     libedit-dev libxml2-dev libsqlite3-dev swig 
     
     libpython-dev libncurses5-dev pkg-config
				

Who uses Swift?


  • Apple
  • Lyft
  • LinkedIn
  • Coursera
  • IBM
  • Mozilla
  • Facebook

Starting out...


Once installed, Swift can be called from the terminal

Basic Concepts


Comments are done by using // for a single line and /* */ for multiple lines.


It's not mandatory or even necessary to end each line with ";" but when you have a C++ background...


Precedence must be enforced by parenthesis

				
print(2*3+5);

11


print(2*(3+5));

16
				

Basic Concepts


Printing on the screen is easy...

				
var text: String = "This is Swift";



print(text); 



This is Swift!
				

Declare the variable type is not mandatory, but makes the code easier to read...

Variables can have multi-assignments...


				
var (a: Int, b: Int, c: Int) = (1, 2, 3);



print(a, b, c);



1 2 3
				

Data Structures


We can declare variables and constants

Variables can change while constants can not...

				
var s_variable:String = "This is a string variable";


var i_variable:Int = 2016;


let variable:Int = 2015;


variable = 2016;


//error: repl.swift:12:10: error: cannot assign to 

//value: 'constant' is a 'let' constant
				

Arrays and Hashes

				
let programming: [String] = ["Forth", "Lua", 


                             "Haskell", "Swift"];



let programming_types: [String : String] = [


    "Forth" : "Stack Based",

	
    "Lua" : "Imperative",

	
    "Haskell" : "Functional",


    "Swift" : "Multi-paradigm"
]
				

We can also create nested arrays

				
let one: [String] = ["one", "two", "three"];


let two: [String] = ["four", "five", "six"];


let three: [[String]] = [one, two];


print(three[1][2]);


six
				

or hashes/dictionaries

				
let one: [String:String] = ["1":"One","2":"Two"];


let two: [String:String] = ["3":"Three","4":"Four"];


let three: [String:[String:String]] = 


           ["One":one, "Two":two];


print(three["Two"]!["4"]!);


four
				

If you wonder about the "!" symbol...it's because Swift consider optional values...if we don't use "!" we will end up with "optional four" and some warnings...

Operations on Arrays

								
var programming = [String](); //Creates empty array


programming.append("Erlang");


programming.insert("Falcon", at: 0);


programming.append("Visual Basic");


programming.removeLast();


print(programming);



["Falcon", "Erlang"]
				

Operations on Hashes/Dictionaries

				
var programming = [String: String](); //Empty hash


programming["Haskell"] = "Functional";


programming["Visual Basic"] = "Event Oriented";


programming["Visual Basic"] = nil;


print(programming);



["Haskell": "Functional"]
				

Functions

Functions are very interesting...and a lot can be learned...

				
func greet(name:String,age:Int){
	
    print("Hello \(name), you're \(age) years old!");

}



func greet(name:String) -> String{

    return "Hello \(name)!";

}



greets(name:"Blag",age:39);

print(greet(name:"Blag"));
				


  • Functions can return or not values

  • \() is used for string interpolation

  • When calling a function the parameter name must be specified

  • Unless we declare it like this "_ name:String"

  • Two function can have the same but different parameters

  • Function can have another functions...

  • Function can return multiple values...

Functions inside functions

				
func greeting(name:String) -> ((String) -> String){
	
   func addlocation(location:String) -> String{
	
        return "Hello \(name)!" + 
                
               "Greetings from \(location)";
	
    }
	
    return addlocation;

}


var greetme = greeting(name:"Blag");

print(greetme("Palo Alto"));



Hello Blag! Greetings from Palo Alto
				

Returning multiple values

				
func operations(num:Int) -> (a:Int, b:Int, c:Int){
    
    let a = num * 2;
    
    let b = num * 3;
    
    let c = num * 4;
    
    return (a,b,c);

}



let squares = operations(num:2);


print(squares.a);

print(squares.b);

print(squares.c);
				

map


Map is a very powerful command that allows us to apply a function to each value of an array

				
let numbers = [1, 2, 3];


let test = numbers.map{$0 * 3};


print(test);


3, 6, 9
				

Classes

Being multi-paradigm...Swift allows us to create classes as well...

				
class Person{

	var name:String;

	var age:Int;
	

	init(name:String,age:Int){

		self.name = name;

		self.age = age;

	}
	

	func getDescription() -> String{

		return "\(name) is \(age) years old.";

	}

}
				

				
var Blag = Person(name:"Blag", age:39);

print(Blag.getDescription());



Blag is 39 years old.
				

Fibonacci List


Finally...we're going to make our first application...


So grab your favorite text editor and get ready...


Name your file "fibonacci.swift"


				
func fib(num:Int,a:Int,b:Int) -> String{

    var result: String = "";

    if a > 0 && num > 1{

        result = result + String(a + b) + " " + 

                 fib(num:(num - 1), a:(a + b), b:a);

    }else if a == 0{

        result = String(a) + " " + String(b) + " " + 

                 String(a + b) + " " + 

                 fib(num:(num - 1), a:(a + b), b:b);

    }

    return result;

}
				
				
print("Enter a number: ",terminator:"");

let number = Int(readLine(strippingNewline: true)!);



print(fib(num: number!, a: 0, b: 1));
				

Open the Terminal and go to your source code folder...

Swift "Name_of_File.swift"


When we run it we're going to see...

Making an LED Number App


This is one of my favorite codes of all time...


Name your file "LED_Numbers.swift"


				
let leds: [Character:String] = [


    "0" : " _  ,| | ,|_| ", "1" : "  ,| ,| ",


    "2" : " _  , _| ,|_  ", "3" : "_  ,_| ,_| ",


    "4" : "    ,|_| ,  | ", "5" : " _  ,|_  , _| ",


    "6" : " _  ,|_  ,|_| ", "7" : "_   , |  , |  ",


    "8" : " _  ,|_| ,|_| ", "9" : " _  ,|_| , _| "


];
				
				
print("Enter a number: ",terminator:"");

let num = readLine(strippingNewline: true);



var line = [String]();

var led = "";


for i in 0...2{

    for character in num!.characters{

        line = String(leds[character]!)!.
        
               characters.split(separator: ",").
               
               map(String.init);

        print(line[i], terminator:"");

    }

    print("");

}

				

When we run it we're going to see...


Random Names


This App will generate 100,000 random names using two 16 elements arrays


We will measure the runtime


Name your file "Random_Names.pl"


				
import Foundation;


let start = NSDate();



let names: [String] = [

    "Anne","Gigi","Blag","Juergen","Marek","Ingo", 
    
    "Lars","Julia","Danielle","Rocky","Julien","Uwe",
    
    "Myles","Mike","Steven","Fanny"

];
				
				
let last_names: [String] = [

    "Hardy", "Read", "Tejada", "Schmerder", 
    
    "Kowalkiewicz", "Sauerzapf", "Karg", 
    
    "Satsuta", "Keene", "Ongkowidjojo", 
    
    "Vayssiere", "Kylau", "Fenlon", 
    
    "Flynn", "Taylor", "Tan"
];



let time = UInt32(NSDate().

           timeIntervalSinceReferenceDate)

srand(time)



var full_names = [String]();

var full_name:String;
			
				
for i in 1...1000000{

	full_name = names[Int(rand()%16)] + " " + 
	
	            last_names[Int(rand()%16)];

	full_names.append(full_name);

}




let elapsed = abs(start.timeIntervalSinceNow);


print("Time: \(elapsed)");


print("\(full_names.count) names generated");
			

When we run it we're going to see...

How this behaves in Python?

And in Julia?

Decimal to Romans


This App will create a Roman Numeral based on a decimal number


This will include some nice commands...


Name your file "decimal_to_romans.swift"


				
let roman_table: [Int:String] = [

    
    1000:"M", 900:"CM", 500:"D", 400:"CD", 100:"C", 
    
    
    90:"XC", 50:"L", 40:"XL", 10:"X", 9:"IX", 5:"V", 
    
    
    4:"IV", 1:"I"

];
			
				
func roman_number(num:Int) -> String{

    var result:String = ""; var number = num;

    let sortedKeys = Array(roman_table.keys).
    
                     sorted(by: >);

    while number > 0{

        for value in sortedKeys{

            if number >= value{

                result = result + roman_table[value]!;

                number -= value; break;

            }

        }

    }

    return(result);

}
			
				
print("Enter a number: ",terminator:"");

let number = Int(readLine(strippingNewline: true)!);



print(roman_number(num:number!));
				

When we run it we're going to see...


That's it for now


Swift is a pretty awesome language...for Mac's


The porting to Linux is too fresh to expect having everything implemented...


As new and updated versions keep comming up...will see how good Swift becomes for Linux...


Contact Information


Blag --> blag@blagarts.com

@Blag on Twitter

Go back home...