My Swift Cookbook

Variable Declaration

Normal Declaration

1
2
3
4
5
6
7
8
9
// Constant
let constantA = "constantA"
let constantA:String = "this is a string"

// Variable
var variableA = "variableA"

// Multiple assignment
var variableB = 0, variableC = 1, variableD = 3.0

Casting

Bridging

Control Flow

Tuple

Function & Closure

Declaration

1
2
3
4
5
6
7
8
9
  func hello(message: String) {}
  func addTen(number: Int) -> Int {}
  func sum(numbers: Int...) -> Int {}

  // Passing function as arguement
  func filter(numbers: [Int], filteringFuntion: Int -> Bool) -> [Int] {}

  // Returning function
  func getTheFunction() -> ([Int] -> Bool)

Class

Declaration

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class MyClass {

  var myVariable = "text"
  var anotherVariable:String

  init() {
    
  }

  deinit() {

  }

  func hiDude() -> String {
    return "Hi dude!"
  }

  func hiDudeNoReturn() {
    ....
  }

  func hiDudeNoReturnAgain() -> Void {

  }

  func sayMyName(name: String) -> Void {

  }

}

class MyChildClass : MyClass {
  override func hiDude() -> String {

  }
}

Struct

String

A thing that does not make me feel nature here is that String is a Struct. It is a value type, not a reference type. When you pass the string as a method arguement, it’s passed by value. Also, you can not use operator like === with string.

String substitution

1
var text = "this is a \(anotherString)"

Array

Declaration

1
2
3
4
5
6
var array1 = [1,2,3,4]
var array2 = Array<String>()
var array3:[String] = ["aaa", "bbb"]

array1[0...2] = [11,22,33] // array1 = [11,22,33,4]
array1[0..<2] = [55,66] // array1 = [55,66,33,4]

Iteration

1
2
3
4
5
6
7
8
9
var array1 = [1,2,3,4]
for item in array1 {
  item
}

for (index, value) in array1 {
  index
  value
}

Dictionary

Declaration

1
2
3
4
5
6
var dict = [ 
  "key" : "value"
]

var dict2: [String : String]
var dict3: Dictionary<String, String>

Accessing the keys and values

1
2
3
4
5
6
7
var dict = [ 
  "key1" : "value1"
  "key2" : "value2"
]

var keys = Array(dict.keys)
var values = Array(dict.values)

By accessing the dict.keys and dict.values, Swift will try to figure out what type of stuff lying inside the collection. .. This is quite messed for me though, I can’t say var keys:[AnyObject] = Array(dict), swift will force the return value as [String].

Iteration

1
2
3
4
var dict = [ 
  "key1" : "value1"
  "key2" : "value2"
]

Comments