Супер простой синтаксис замыкающего замыкания в Swift - PullRequest
0 голосов
/ 23 марта 2019

Я пытаюсь следовать примеру в документах Swift для трейлинг-закрытия.

Это функция:

func someFunctionThatTakesAClosure(closure: () -> Void) {
    // function body goes here
    print("we do something here and then go back")//does not print
}

И я называю это здесь.

        print("about to call function")//prints ok
        someFunctionThatTakesAClosure(closure: {
            print("we did what was in the function and can now do something else")//does not print
        })
        print("after calling function")//prints ok

Функция, однако, не вызывается. Что не так с вышесказанным?

Вот пример Apple:

func someFunctionThatTakesAClosure (closure: () -> Void) { // здесь идет тело функции}

// Вот как вы вызываете эту функцию без использования завершающего замыкания:

someFunctionThatTakesAClosure (закрытие: { // тело замыкания идет сюда})

Ответы [ 2 ]

1 голос
/ 23 марта 2019

Вот ваш пример исправления:

func someFunctionThatTakesAClosure(closure: () -> Void) {
    // function body goes here
    print("we do something here and then go back")

    // don't forget to call the closure
    closure()
}


print("about to call function")

// call the function using trailing closure syntax
someFunctionThatTakesAClosure() {
    print("we did what was in the function and can now do something else")
}

print("after calling function")

Вывод:

about to call function
we do something here and then go back
we did what was in the function and can now do something else
after calling function
1 голос
/ 23 марта 2019

Документы не очень понятны в объяснении, которое вам нужно

print("1")
someFunctionThatTakesAClosure() {  // can be also  someFunctionThatTakesAClosure { without ()
    print("3") 

}

func someFunctionThatTakesAClosure(closure: () -> Void) { 
   print("2") 

   /// do you job here and line blow will get you back
    closure()
}  

замыкающее замыкание предназначено для завершения, например, когда вы делаете сетевой запрос и, наконец, возвращаете ответ, подобный этому

func someFunctionThatTakesAClosure(completion:  @escaping ([String]) -> Void) { 
   print("inside the function body") 
   Api.getData { 
      completion(arr)
   }
}  

И чтобы позвонить

print("Before calling the function")
someFunctionThatTakesAClosure { (arr) in
  print("Inside the function callback  / trailing closure " , arr)
}
print("After calling the function") 

что вы пропустили, чтобы прочитать

enter image description here

...