CompletionHandler и закрытие - PullRequest
       22

CompletionHandler и закрытие

0 голосов
/ 04 января 2019

У меня есть несколько вопросов здесь,

1) Что такое CompletionHandler и Closure и когда его использовать?2) Закрытие против CompletionHandler

это немного сбивает с толку.

1 Ответ

0 голосов
/ 04 января 2019

Обработчик завершения и закрытие являются синонимами.Они называются блоками в Objective-C.

Вы можете думать о них как об объектах, которые выполняют блок кода при их вызове (очень похоже на функцию).

// My view controller has a property that is a closure
// It also has an instance method that calls the closure
class ViewController {

    // The closure takes a String as a parameter and returns nothing (Void)
    var myClosure: ((String) -> (Void))?
    let helloString = "hello"

    // When this method is triggered, it will call my closure
    func doStuff() {
        myClosure(helloString)?
    }
}

let vc = ViewController()

// Here we define what the closure will do when it gets called
// All it does is print the parameter we've given it
vc.myClosure = { helloString in
    print(helloString) // This will print "hello"
}

// We're calling the doStuff() instance method of our view controller
// This will trigger the print statement that we defined above
vc.doStuff()

ЗавершениеОбработчик - это просто замыкание, которое используется для выполнения определенного действия: когда вы закончите что-то делать, вы вызываете обработчик завершения, который выполняет код для завершения этого действия.

Это просто базовое объяснение, для более подробной информацииВы должны проверить документы: https://docs.swift.org/swift-book/LanguageGuide/Closures.html

...