Swift - How to know when a loop has ended?

前端 未结 5 1765
我寻月下人不归
我寻月下人不归 2020-12-30 11:52

Please, forgive me as i\'m very new to swift, and programming in general.

Believe me when I say I\'ve tried hard to understand this, but I simply ca

5条回答
  •  余生分开走
    2020-12-30 12:37

    To produce the same result as what others have posted but with basic closure syntax:

    func printFunction() {
        println("loop has finished")
    }
    
    func loopWithCompletion(closure: () -> ()) {
        for var i=0; i<5; i++ {
            println(i)
        }
        closure()
    }
    

    This is how you call it:

     loopWithCompletion(printFunction)
    

    Swift 3 Update:

    func printFunction() {
        print("loop has finished")
    }
    
    // New for loop syntax and naming convention
    func loop(withCompletion completion: () -> Void ) {
        for i in 0 ..< 5 {
            print(i)
        }
        completion()
    }
    

    Then call it like this:

    loop(withCompletion: printFunction)
    

    Or

    loop {
        print("this does the same thing")
    }
    

提交回复
热议问题