Zoeken…


Invoering

Functies zoals First Class-leden bedoelen, het kan genieten van privileges, net als Objects. Het kan worden toegewezen aan een variabele, worden doorgegeven aan een functie als parameter of kan worden gebruikt als retourtype.

Functie toewijzen aan een variabele

struct Mathematics
{
    internal func performOperation(inputArray: [Int], operation: (Int)-> Int)-> [Int]
    {
        var processedArray = [Int]()
        
        for item in inputArray
        {
            processedArray.append(operation(item))
        }
        
        return processedArray
    }
    
    
    internal func performComplexOperation(valueOne: Int)-> ((Int)-> Int)
    {
        return
            ({
                 return valueOne + $0   
            })
    }
    
}


let arrayToBeProcessed = [1,3,5,7,9,11,8,6,4,2,100]

let math = Mathematics()

func add2(item: Int)-> Int
{
    return (item + 2)
}

// assigning the function to a variable and then passing it to a function as param
let add2ToMe = add2
print(math.performOperation(inputArray: arrayToBeProcessed, operation: add2ToMe))

Output:

[3, 5, 7, 9, 11, 13, 10, 8, 6, 4, 102]

Evenzo kan het bovenstaande worden bereikt met behulp van een closure

// assigning the closure to a variable and then passing it to a function as param
let add2 = {(item: Int)-> Int in return item + 2}
print(math.performOperation(inputArray: arrayToBeProcessed, operation: add2))

Functie doorgeven als argument aan een andere functie, waardoor een hogere-orde functie wordt gecreëerd

func multiply2(item: Int)-> Int
{
    return (item + 2)
}


let multiply2ToMe = multiply2

// passing the function directly to the function as param
print(math.performOperation(inputArray: arrayToBeProcessed, operation: multiply2ToMe))

Output:

[3, 5, 7, 9, 11, 13, 10, 8, 6, 4, 102]

Evenzo kan het bovenstaande worden bereikt met behulp van een closure

// passing the closure directly to the function as param
print(math.performOperation(inputArray: arrayToBeProcessed, operation: { $0 * 2 }))

Functie als retourtype van een andere functie

// function as return type
print(math.performComplexOperation(valueOne: 4)(5))

Output:

9



Modified text is an extract of the original Stack Overflow Documentation
Licentie onder CC BY-SA 3.0
Niet aangesloten bij Stack Overflow