简体   繁体   中英

Can swift while loops use functions as parameters?

I'm working on a practice challenge question that uses a online compiler. I've written the code below and it works in Xcode but the online compiler is saying I have it wrong.

Here is my code which I know is right and works in Xcode:

func squareThatNumber(input: Int) -> Int{
            let x: Int = input * input
            return x
        }

        print(squareThatNumber(input: 5))

Maybe I'm not understanding the question because the online compiler is starting off with this code which I've never seen a while loop written this way:

import Foundation

while let line: String = readLine() {
    print(line)
}

Can someone explain what the above code is doing because it compiles in the online compiler but I've never seen a while loop use a function. Any direction or resource explaining this in detail is greatly appreciated.

This code calls readLine() at the start of every iteration. The result of that function is a String? (aka Optional<String> ). If there is really a String there, it'll be bound to the variable line , and the block will be called once. This process is repeated until the binding isn't possible, that is, until readLine() returns nil .

@Alexander answer provides the right information to understand what is happening. After searching SO, this challenge is similar to what is on HackerRank and answered in this SO question as well

The code that worked in this online compiler is the following which Alexander pointed out how it works:

import Foundation

func squareThatNumber(input: Int) -> Int{
            let x = input * input
            return x
        }

while let line: String = readLine() {

    print(squareThatNumber(Int(line)!))

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM