खोज…


परिचय

प्रथम श्रेणी के सदस्यों के रूप में कार्य का अर्थ है, यह विशेषाधिकार का आनंद ले सकता है जैसे ऑब्जेक्ट करता है। यह एक चर को सौंपा जा सकता है, एक फ़ंक्शन पर पैरामीटर के रूप में पारित किया जाता है या रिटर्न प्रकार के रूप में उपयोग किया जा सकता है।

एक चर के लिए कार्य सौंपना

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))

आउटपुट:

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

इसी तरह ऊपर एक 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))

फ़ंक्शन को दूसरे फ़ंक्शन के तर्क के रूप में पारित करना, इस प्रकार एक उच्च-क्रम फ़ंक्शन बनाना

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))

आउटपुट:

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

इसी तरह ऊपर एक closure का उपयोग करके प्राप्त किया जा सकता है

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

किसी अन्य फ़ंक्शन से वापसी प्रकार के रूप में फ़ंक्शन

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

आउटपुट:

9



Modified text is an extract of the original Stack Overflow Documentation
के तहत लाइसेंस प्राप्त है CC BY-SA 3.0
से संबद्ध नहीं है Stack Overflow