Giter VIP home page Giter VIP logo

escaping's Introduction



@escaping 키워드는 언제 사용하는 것일까?


목차


@escaping키워드는 주로 두 가지 경우에서 사용된다


    

  1. 어떤 함수의 내부에 존재하는 closure를 외부 변수에 저장하는 경우
  2. GCD(비동기 코드)를 활용해야하는 경우

내부의 closure를 외부 변수에 저장하는 경우


var aSavedFunction: (() -> ())?

func performEscaping(closure: @escaping() -> ()) {
    aSavedFunction = closure //클로저를 실행하는 것이 아닌 외부 변수 aSavedFunction 에 저장
}
  1. performEscaping()의 경우 단순히 Stack에 올라갔다 사라지는 것이 아닌 외부 변수(Heap 메모리)에 클로저를 넣고있다.
  2. 이때 Stack frame을 벗어나서 Heap에 내부 closure를 할당하고 있다는 것을 알려주어야 하는데 이때 @escaping키워드를 활용한다
  3. 단순히 말하자면 함수 내부의 closure(함수)를 더 길게 사용하고 싶을 때 쓰는 키워드이다.

GCD 비동기 코드를 사용하는 경우

func performEscaping(closue: @escaping() -> ()) {

    let name = "suojae"

    DispathcQueue.global().async {
        closure()
    }
}
  1. DispathcQueue()는 기본적으로 2번 thread에게 일을 시키는 code이다.
  2. 이때 closure를 2번 thread(2번 Stack)에게 일을 시키기 위해서는 main thread(1번 Stack)에서 곧바로 2번 stack에 `closure()'을 보낼 수 없다
  3. 중간다리로 Heap에 저장해두고 1번 Stack(main thread) -> Heap -> 2번 Stack(2nd thread) 으로 진행되는데 이를 위해 @escaping 키워드가 사용된다.

escaping's People

Contributors

suojae3 avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.