Getting Closure on Swift Closures

Korey Hinton -> Blog -> iOS -> Getting Closure on Swift Closures

Closures Defined

A closure is a function that has access to the local variables available at the time it was created or stored into a variable. In other programming languages they are usually called lambdas or anonymous functions and in Objective-C they are called blocks.

Swift Closure Examples

Below is a playground file displaying the different ways to setup or use swift closures.

import Cocoa

/* Without Parameters  */
var voidClosure = {
    () -> Void in
    println("No params & no return value");
}

voidClosure()
//  >> No params & no return value

var stringClosure = {
    () -> String in
    return "No params & this is my returned string"
}

var a : String = stringClosure()
println(a)
//  >> No params & this is my returned string

var b : ()-> String = stringClosure
println(b())
//  >> No params & this is my returned string


/* With Parameters */
var addClosure = {
    (a:Int,b:Int)-> Int in
    return a + b
}

println( addClosure(1,2) )
// >> 3

var adder = addClosure
println( adder(1,2) + adder(1,2) )
// >> 6

/* In method signature */
func multiply(num1: Int, num2: Int, completion: (Int,Bool)-> Void) {
    let product : Int = num1 * num2
    completion(product,product > 0)
}

multiply(5,3,{(product : Int,isGreaterThanZero : Bool) -> Void in
    if isGreaterThanZero {
        println(product)
    }
})


Date: 2014-07-06T04:04+0000

Author: Korey Hinton

Org version 7.9.3f with Emacs version 24

Validate XHTML 1.0