Monday, December 14, 2015

Swift: extension and closure

TutorialPoint web site provides great information about Swift basic and syntax in a serials of sections or courses. While I was reading its content, I also tried to explore codes there with modifications.

Extension and closure or block are very powerful in Swift, but they are hard to understand at the beginning. Although the description in this web tutorial explains well with simple codes, I would like to extend codes with various ways to understand those concepts in Swift.

Following is an example of codes for Int type extension with closure:




Here are my codes based on above example:


extension  Int {
    var increment: Int {return self + 2}
    func repeatBy(n : Int, message: (i: Int, v: Int) ->()) {
        for a in 0..<self {
            let r = a + n
            message(i: a, v:r)
        }
    }
}

let increment = 12.increment
print("12.increment: \(increment)")
increment.repeatBy(5) { (i, v) -> () in
    print("\(i+1) Message: \(v)")
}

The method increment is a very simple one, and I changed increment by 2.

The closure in the method of repeatBy is extended to a method with 2 parameters, and the second parameter is a closure taking two parameters. Within the closure, the first parameter, an external variable (1st parameter) and a local variable are used to call message(...) block.

The exercise codes afterwards uses print() to display a customized string with those two parameters. The result is as follows:


12.increment: 14
1 Message: 5
2 Message: 6
3 Message: 7
4 Message: 8
5 Message: 9
6 Message: 10
7 Message: 11
8 Message: 12
9 Message: 13
10 Message: 14
11 Message: 15
12 Message: 16
13 Message: 17
14 Message: 18


References



0 comments: