WWDC24 SALE: Save 50% on all my Swift books and bundles! >>

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      

Save 50% in my WWDC sale.

SAVE 50% To celebrate WWDC24, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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.