Skip to content

Instantly share code, notes, and snippets.

@pythonicrubyist
Last active August 29, 2015 14:15
Show Gist options
  • Save pythonicrubyist/6ed7a82d13518f36dad3 to your computer and use it in GitHub Desktop.
Save pythonicrubyist/6ed7a82d13518f36dad3 to your computer and use it in GitHub Desktop.
Collections in Swift
// Collections in Swift
// Two basic collection types in Swift, Arrays and Dictionaries.
// Arrays in Swift
// Ordered collections of items
// Zero based.
// Type safe
// If defined by let, it is immutable, can not be added or altered.
// If dfined by var, it is mutable, can be modifed and added.
var a1 = [2, 3, 4]
var a2 : [Int]
a1[2] = 8
a1.append(5)
a1 += [6]
a1.insert(1, atIndex: 0)
a1.removeLast() // removes the last item from array and returns the removed item.
a1.count
for i in a1 {
println(i)
}
// Dictionaries in Swift
// A dictionary is a collection of Key value pairs.
// keys are strrictly typed.
// Values are strictly typed.
var d1 = [1: "One", 2: "Two", 3: "Three"]
var d2 : [Int: String]
d1[4] = "Four"
d1[0] // returns nil
d1[1] //returns "ONe
d1.updateValue("FOUR", forKey: 4)
d1.removeValueForKey(4)
d1.count
for (k, v) in d1{
println("\(k) corresponds to \(v)")
}
// Tuples in Swift
// Tuples are a clollection of any items
var t1 = ("Ruby", 3, true)
// A function can return a tuple
func someFunction() -> (Int, String){
return (2, "Some string")
}
someFunction()
let r1 = someFunction()
r1.0 // returns 2
r1.1 // returns "Some String"
let (r2, r3) = someFunction()
r2 // returns 2
r3 // returns "Some String"
// Optionals in Swift
// The data which is missing and data which is zero(or default) or data which is nil are different.
var temperature :Int? // means that this variable can be an integer or nil
println("Temperature is: \(temperature)") // returns"Temperature is: nil"
temperature = 37
if temperature != nil{
println("Temperature is: \(temperature)") // returns "Temperature is: Optional(37)"
println("Temperature is: \(temperature!)") // returns ""Temperature is: 37""
}
// Enumerators in Swift
enum SteakPreference {
case wellDone
case medium
case rare
case blueRare
}
var mySteakPreference = SteakPreference.medium
var JackSteakPreference : SteakPreference
JackSteakPreference = .wellDone
// Closures in Swift
// A self-cntained, reusable group of code
// A function is a type of closure.
let c1 = {
println("Hello World!")
}
func f1 (c : ()->()){
for i in 1...5 {
c()
}
}
f1(c1)
func f2 ()->(){
println("Hello World!")
}
// Turning aboce function into a closure:
var c2 = {
()->() in
println("Hello World!")
}
f1({()->() in println("Hello World!")})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment