Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save 0xjorgev/09f3f5d155671a88c055 to your computer and use it in GitHub Desktop.
Save 0xjorgev/09f3f5d155671a88c055 to your computer and use it in GitHub Desktop.
Swift Programming Language Quick Reference Guide

Swift Programming Language Quick Reference Guide

 The Swift Programming Language was launch on June 2, 2014 in the Apple WWDC. Since that very same day i started trying this new, modern, simple to read and complex to learn programming language.

 This will be a quick reference guide for Swift. Let's start by describing the basic things first.

Variables in Swift

Variables are values and objects containers in the Swift Programming Language, variables are declared using the let reserved word for constants and var for mutable ones, lets see some variables examples. ```swift

//Implicit inmutable variable let dojoNinjas = 1 //Implicit mutable variable var ninjaApprentices = 1500

//Explicit inmutable variable let masterNinjas:Int = 0 //Explicit mutable variable var ninjaStars:Int = 500

//Implicit String variable var secrettNinjaMessage = "Do or do not, there is no try!" //Explicit String variable var faketNinjaMessage:String = "Fear is the path into the Darkside"

 

Also the variables object type might be declared (explicit) or not (implicit).
<h2 style="text-align: left;"> Arrays in Swift</h2>
Arrays are containers for objects of the same type. Swift allows arrays creation also implicitly or in a explicit way, have a look.
```swift

//Arrays
//Constant Implicit Array of Strings
let ninjaWeapons = ["knife", "Swords", "Say", "Bo", "daggers", "stars", "Bow and Arrow"]
//Explicit Array of Strings
var ninjaMoves:[String] = ["Dodge", "Hand Attack", "Kick", "Hide", "Jump", "Fatality"]

 

Arrays are very handy and provides several functions, let's play a bit with some of the basic arrays functions.

//Array Cont
let weaponsInventory:Int = ninjaWeapons.count
//Array Object at index 2, position 3 (index starts with 0)
var favoriteWeapon:String = ninjaWeapons[2]

//Add new element to the array
ninjaMoves.append("Smoked Ilutions")
//Object at index 2, position 3
ninjaMoves[2]

 

 Control Flow in Swift

The Swift Programming Language came with several new things and the control flow structures is one of those things. The first difference is the absence of "()" to express a condition. If you come from the Objective-C World (like me) there are a few very handful things, like operators that controls ranges in loops.
//Compare between Integer values
if weaponsInventory > 0 {
    println("Ready to Attack")
} else {
    println("Hide instead")
}

var enemiesHitedWithArrows:Int = 0

//Flow control in For Loops
for arrow in 0 ... 99 {
    
    let posibility:Float = Float(arc4random_uniform(2))
    //Posibles values 0 and 1
    
    if posibility == 1 {
    
        enemiesHitedWithArrows++
    }
    
    println("You've thrown \(arrow) arrows and hitted \(enemiesHitedWithArrows) ninja enemies ")
}

1 == 1   // true, because 1 is equal to 1
2 != 1   // true, because 2 is not equal to 1
2 > 1    // true, because 2 is greater than 1
1 < 2    // true, because 1 is less than 2
1 >= 1   // true, because 1 is greater than or equal to 1
2 <= 1   // false, because 2 is not less than or equal to 1

let hitCounter = 35

switch(hitCounter){
    case 0 ... 5 :
        println("Time to strat attacking!")
    case 6 ... 10 :
        println("Time to Jump!")
    case 10 ... 35 :
        println("Fatality attack time")
    default:
        println("Calm your mind and meditate your position")
}

 

Another great feature in Swift is enumerations, similar to the enums in Objective-C but better, the best companion of enums is the switch and now they got simpler than the Objective-C version (you don't need to add break sentences in each case)

//Enumeration
enum attack {
    
    case fast
    case silence
    case deadly
}

let myNinjaAttack:attack = .fast

//Switch and Enums
//This is an untyped enum
switch (myNinjaAttack){
    
case .fast:
    println("Fast as an eagle Attack!")
case .silence:
    println("Silent as a snake attack!")
case .deadly:
    println("The Black Mamba attack!")
}

 

 Functions in Swift

Functions in Swift and i quote "functions are first class citizens in Swift", this concept shows up in every mayor post about Swift and is related to funcional programming that is a new paradigma that swift allows us to implement in our projects. However functions are a piece of code that executes a specific task. The have their own name, name used to call that function. In Swift functions can have parameters (in values) and type (the output value)
//Simple Void Function
func simpleNinjaFunction(){
    println("This is prety much it ... 👍")
}

//Void Function with Parameters
func parameterFunction(att:attack){
    println("The attack description is \(att)")
}

//Type String Function with Parameters
func ninjaAttackDescription(att:attack) -> String {
    
    switch (myNinjaAttack){
        
    case .fast:
        return "Fast as an eagle Attack!"
    case .silence:
        return "Silent as a snake attack!"
    case .deadly:
        return "The Black Mamba attack!"
    }
}

//Type Int Function with Parameters
func numberOfWeapons(weapons:[String]) -> Int {
    
    return weapons.count
}

 

 Classes in Swift

Classes in Swift like any other Object Oriented Programming Language are structures used to build objects, in a simpler way of speak they are the blue prints of our objects. Classes might contain all the elements described in this post and many other (that i will write about in future posts ...)
//Classes
class Ninja:NSObject {
    
    let secrettMessage:String
    let weapons:[String]
    let moves:[String]
    var favoriteWeapon:String
    var color:UIColor
    var attackStyle:attack
    var arrowInventory:Int
    
    init(message:String, weapons:[String], moves:[String],favWeapon:String, color:UIColor, style:attack, arrows:Int) {
        self.secrettMessage = message
        self.weapons = weapons
        self.moves = moves
        self.favoriteWeapon = favWeapon
        self.color = color
        self.attackStyle = style
        self.arrowInventory = arrows
    }
    
    func setFavWeapon(index:Int){
        
        self.favoriteWeapon = weapons[index]
    }
    
    func setColor(color:UIColor){
        self.color = color
    }
    
    func performRandomMove() ->String {
        
        let index:Int = Int(arc4random_uniform(UInt32(self.moves.count)))
        return self.moves[index]
    }
    
    func throwArrow() -> Bool {
        
        let posibility:Float = Float(arc4random_uniform(2))
        //Posibles values 0 and 1
        self.arrowInventory--

        if posibility == 1 {
            return true
        } else {
            return false
        }
    }
    
    func throwArrowAttack() ->Self {
        self.arrowInventory--
        return self
    }
    
    func printArrowsLeft(){
        
        println("Arrows lefts: \(self.arrowInventory)")
    }
}

//Class initialization
var eliteNinja:Ninja = Ninja(message: secrettNinjaMessage, weapons: ninjaWeapons, moves: ninjaMoves, favWeapon: ninjaWeapons[2], color:UIColor.clearColor(), style: attack.silence, arrows:50)
eliteNinja.setColor(UIColor.blueColor())
eliteNinja .throwArrow()
//Print the amount of remaining amount of arrows
eliteNinja.printArrowsLeft()
//Continuos attacks!
eliteNinja.throwArrowAttack().throwArrowAttack().throwArrowAttack().throwArrowAttack()
eliteNinja.printArrowsLeft()

 

 Conclusions

The Swift Programming Language is a modern simple to understand yet not so simple to use language. It comes with a huge kit of tools that allows developers to create awesome pieces of software and great apps with less code that it's predecesor Objective-C. There is so much to cover about Swift, Stay tuned! Keep Coding!

Find More about Swift in theswift.ninja

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment