GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

SOLVED: What is "using" term doing there?

Forums > 100 Days of SwiftUI

https://www.hackingwithswift.com/quick-start/beginners/how-to-accept-functions-as-parameters#:~:text=func%20makeArray(size%3A%20Int%2C%20using%20generator%3A%20()%20%2D%3E%20Int)%20%2D%3E%20%5BInt%5D%20%7B%0A%20%20%20%20var%20numbers%20%3D%20%5BInt%5D()%0A%0A%20%20%20%20for%20_%20in%200..%3Csize%20%7B%0A%20%20%20%20%20%20%20%20let%20newNumber%20%3D%20generator()%0A%20%20%20%20%20%20%20%20numbers.append(newNumber)%0A%20%20%20%20%7D%0A%0A%20%20%20%20return%20numbers%0A%7D

func makeArray(size: Int, using generator: () -> Int) -> [Int] {
    var numbers = [Int]()

    for _ in 0..<size {
        let newNumber = generator()
        numbers.append(newNumber)
    }

    return numbers
}

What is the purpose of "using" term before generator closure? It looks like as "argument label" but it is not used in the code example when calling the makeArray function and it does not seem to be logical to use an argument label for a closure.

   

It's an argument label for the generator parameter name.

Argument labels are used externally, when calling a function.

Parameter names are used internally inside the function's code.

So you call this function using the argument label like:

let newRolls = makeArray(size: 50, using: generateNumber)

But inside the function, you use that parameter name to call the function or closure that was passed in:

let newNumber = generator() 

In other words:

  • using = argument label referring to a function or closure passed into makeArray
  • generator = parameter name for the same function or closure

1      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's all new Paywall Editor allow you to remotely configure your paywall view without any code changes or app updates.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.