I started learning Swift and functions, and I ran into a problem. Tell me how to understand the below code:

func genWallet (walletLength: Int) -> [Int] { let typesOfBanknotes = [50, 100, 200, 500] var wallet: [Int] = [] for _ in 1...walletLength { let randomIndex = Int( arc4random_uniform( UInt32( typesOfBanknotes.count - 1 ) ) ) wallet.append(typesOfBanknotes[randomIndex]) } return wallet } func sumWallet( banknotFunction wallet: (Int) -> ([Int]) ) -> Int? { let myWalletArray = wallet( Int( arc4random_uniform(10) ) ) var sum: Int = 0 for oneBanknote in myWalletArray { sum += oneBanknote } return sum } sumWallet(banknotFunction: genWallet) 

Why does sumWallet (banknotFunction: genWallet) work?

func genWallet (walletLength: Int) requires the same walletLength parameter at the input, but I do not specify it!

Where does the value of walletLength come from in this function?

    2 answers 2

    You can parse line by line:

     sumWallet(banknotFunction: genWallet) 

    calls sumWallet with an argument by a function genWallet type (Int) -> ([Int]) . Go to sumWallet

     let myWalletArray = wallet( Int( arc4random_uniform(10) ) ) 

    when the wallet argument is called with the Int( arc4random_uniform(10) ) parameter Int( arc4random_uniform(10) ) , and this function is defined as genWallet in the call, the following Int( arc4random_uniform(10) ) parameter occurs Int( arc4random_uniform(10) ) is passed to the genWallet function. Then it executes the genWallet and the result is written to the let myWalletArray . Well, then I think it is not necessary to explain ...

      I do not know swift, but it is easy to see that sumWallet accepts the function, and already inside this argument is applied, generated randomly using arc4random_uniform. That is, at the moment sumWallet is called, you only need to know the name of the function, and the actual argument is already passed inside.

      • But before arc4random_uniform there is a for _ in 1 ... walletLength and again the question is where does it come from? - Petrov Kirill
      • @PetrovKirill it is generated in the first line inside sumWallet. - αλεχολυτ
      • then sort the line: func sumWallet (banknotFunction wallet: (Int) -> ([Int])) -> Int? banknotFunction is a function of genWallet. Is a wallet a return wallet from the genWallet function? And (Int) is let myWalletArray = wallet (Int (arc4random_uniform ((10))))? - Petrov Kirill
      • @PetrovKirill banknotFunction - this is the label of the argument ( Argument Label ). A wallet is a function of genWallet. - αλεχολυτ