Level : WORDPRESS BOOK LINKEDIN PATENT Send Mail 동냥하기 hajunho.com

+ 원리, 그래픽 소스까지 넣으면 복잡.

클로저는 간단하다.


import UIKit


func textT(_ first : ()-> (), _ second : ()-> ()) {

    first()

    second()

}


textT( { print("first") }, { print("second") })




보통 클로저는 하나만 쓰기 때문에 ()를 닫아 버리고 {} 로 대체 가능하다.


import UIKit


func textT(_ first : ()-> (), _ second : ()-> ()) {

    first()

    second()

}


textT( { print("first") }) { print("second") }


class ViewController: UIViewController {

    

    func textT(_ first : ()-> (), _ second : ()-> ()) {

        first()

        second()

    }

    

    override func viewDidLoad() {

        textT( { print("first") }) { print("second") }

    }

}

REST API를 쓴다면 필시 Alamofire를 이용하리라 생각된다.

클로저를 이용하면, DispatchQueue를 이용하지 않고 동기화를 할 수 있다.


make func getJSON() to func getJSON(_ whatUwant2execute : @escaping () -> () )


and use your function


getJSON { ... codes ... }


and choose the location you want to execute in Alamofire


getJSON(_ whatUwant2execute : @escaping () -> () ) { Alamofire.request(.GET, "http://announcement.vassy.net/api/AnnouncementAPI/Get/").responseJSON {

 (Response) -> Void in     // checking if result has value    

   if let value = Response.result.value {         

    let json = JSON(value)         

    whatUwant2execute()        

    .        

    .        

    .

then ... codes ... will be executed on that point.


결국 클로저는 함수 포인터고 함수를 실행할 때 쓰는 ()를 이용해서 트리거 시킨다가 요점.


내가 말하고 싶은 더블 클로저는 파라미터 2개인 클로저가 아니라 2차 포인터 처럼 클로저 안에 클로저를 말한다. 포인터를 C의 함수 포인터로 이해하면 쉽지만 이론 설명은 생략. 바로 코드로... 위 소스에서 두번째 클로저는 지웠다. 이름을 바꾸고 클로저 안에 클로저를 넣으면 된다. 흔적 따라오라며 다 바꾸진 않음


import UIKit


func progressBar(_ first : ((Int)->())-> ()) {

    first() { (s) in

        print(s, " %")

    }

}


progressBar() { (closure) -> () in

    print("hello msg")

    closure(10)

    print("checking new version of software")

    closure(20)

    print("connect to the updating server")

    closure(50)

    print("download loop")

    closure(100)

}


핵심은 progress를 담고 있는 var 를 없애는 함수형 프로그래밍을 한다는데 있다. 내가 생각하는 함수형 프로그래밍은 메모리를 삭제 과정 없이 계속 리니어하게 써서 속도를 향상 시키는데 있다고 믿지만, 어느 순간 변질 된 듯. 리눅스 커널 분석하며 어려운 함수 포인터를 typedef 로 무한적 래핑할 수 있는 제자들은 이해가 쉬울 듯.


트리블 클로저를 이용하면 updating 되고 있는 프로그레스바를 더욱 스무스하게 만들 수 있다.


하드웨어 발전 속도만 믿고 뱅글 뱅글 도는 기다림표로 점철되어진 안타까운 소프트웨어에 활력을!


그리고 팁...


FYI,

Plz remember () is used 2 ways "make something in memory" or "executing"

In swift world {} is the meaning of one of the (), executing.

This is the reason why you don't need to write like a below

getJSON ({ ... codes ... })

and {} is the meaning of the definition of functions body.

Both () and {} have two meanings we have to know.

망할 스택 오버플로우에 앞으로 답변하나 봐라. 대한민국 프로그래머 만세


  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기