developer tip

Swift에서 완료 핸들러로 함수를 어떻게 만들 수 있습니까?

optionbox 2020. 8. 17. 08:47
반응형

Swift에서 완료 핸들러로 함수를 어떻게 만들 수 있습니까?


나는 이것에 어떻게 접근할지 궁금했습니다. 함수가 있고 그것이 완전히 실행되었을 때 어떤 일이 일어나기를 원했다면 어떻게 이것을 함수에 추가할까요? 감사


네트워크에서 파일을 다운로드하는 다운로드 기능이 있고 다운로드 작업이 완료되면 알림을 받고 싶다고 가정 해 보겠습니다.

typealias CompletionHandler = (success:Bool) -> Void

func downloadFileFromURL(url: NSURL,completionHandler: CompletionHandler) {

    // download code.

    let flag = true // true if download succeed,false otherwise

    completionHandler(success: flag)
}

// How to use it.

downloadFileFromURL(NSURL(string: "url_str")!, { (success) -> Void in

    // When download completes,control flow goes here.
    if success {
        // download success
    } else {
        // download fail
    }
})

도움이되기를 바랍니다. :-]


간단한 Swift 4.0 예제 :

func method(arg: Bool, completion: (Bool) -> ()) {
    print("First line of code executed")
    // do stuff here to determine what you want to "send back".
    // we are just sending the Boolean value that was sent in "back"
    completion(arg)
}

사용 방법:

method(arg: true, completion: { (success) -> Void in
    print("Second line of code executed")
    if success { // this will be equal to whatever value is set in this method call
          print("true")
    } else {
         print("false")
    }
})

답을 이해하는 데 어려움이있어서 저와 같은 다른 초보자도 저와 같은 문제가있을 수 있다고 가정합니다.

내 솔루션은 최상위 답변과 동일하지만 초보자 또는 일반적으로 이해하기 어려운 사람들에게 조금 더 명확하고 이해하기 쉽기를 바랍니다.

완료 처리기를 사용하여 함수를 만들려면

func yourFunctionName(finished: () -> Void) {

     print("Doing something!")

     finished()

}

기능을 사용하려면

     override func viewDidLoad() {

          yourFunctionName {

          //do something here after running your function
           print("Tada!!!!")
          }

    }

귀하의 출력은

Doing something
Tada!!!

도움이 되었기를 바랍니다!


We can use Closures for this purpose. Try the following

func loadHealthCareList(completionClosure: (indexes: NSMutableArray)-> ()) {
      //some code here
      completionClosure(indexes: list)
}

At some point we can call this function as given below.

healthIndexManager.loadHealthCareList { (indexes) -> () in
            print(indexes)
}

Please refer the following link for more information regarding Closures.

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html


I'm a little confused about custom made completion handlers. In your example:

Say you have a download function to download a file from network,and want to be notified when download task has finished.

typealias CompletionHandler = (success:Bool) -> Void

func downloadFileFromURL(url: NSURL,completionHandler: CompletionHandler) {

    // download code.

    let flag = true // true if download succeed,false otherwise

    completionHandler(success: flag)
}

Your // download code will still be ran asynchronously. Why wouldn't the code go straight to your let flag = true and completion Handler(success: flag) without waiting for your download code to be finished?


In addition to above : Trailing closure can be used .

downloadFileFromURL(NSURL(string: "url_str")!)  { (success) -> Void in

  // When download completes,control flow goes here.
  if success {
      // download success
  } else {
    // download fail
  }
}

참고URL : https://stackoverflow.com/questions/30401439/how-could-i-create-a-function-with-a-completion-handler-in-swift

반응형