[swift] 클로져 (closure)

Snyong·2023년 9월 28일

swift

목록 보기
6/10
post-thumbnail

closure?

  • 이름이 있는 클로져 -> 함수
  • 이름이 없는 클로져 -> 지금 다루는 내용. 어떤 태스크를 수행하기 위한 코드 블럭
// closure의 기본 형태

{ (parameters) -> return type in

	statements
    
}
  • ìn 을 기준으로 클로져 선언부클로져 실행부 가 나뉨
  • 클로져 선언부: 파라미터, 리턴타입 명시
  • 클로져 실행부: 실행 코드 작성
  • swift에서는 클로져, 함수를 타입으로 사용할 수 있음
  • 따라서 변수에 할당하거나, 다른 함수의 파라미터로 전달하는 것도 가능

closure 만들기

let checking = {
    print("checking")
}

checking()

input parameter

  • 클로져도 파라미터를 받을 수 있음
let checking = { (id:String) -> Void in
    print("checking id: \(id)")
}

checking("user123")

returning value

let checking = { (id: String) -> Bool in
    if id == "User000" {
        return false
    }
    return true
}

let isValid1 = checking("User123") // true
let isValid2 = checking("User000") // false

closure as parameter

  • 클로져는 함수 파라미터로 받을 수 있음
let checking = { (id: String) -> Bool in
  if id == "User000" {
        return false
    }

    return true
}


func validate(id: String, checking: (String) -> Bool) -> Bool {
    print("ready..")
    let isValid = checking(id)
    return isValid
}

let validationResult = validate(id: "User002", checking: checking)
let printHello = {
    print("hello swift")
}

func doSomeClosure(_ action: () -> Void) {
    action()
}

doSomeClosure(printHello)
  • closure를 따로 만들어놓지 않고, 함수 수행시 바로 작성할 수도 있다
let checking = { (id: String) -> Bool in
  if id == "User000" {
        return false
    }

    return true
}


func validate(id: String, checking: (String) -> Bool) -> Bool {
    print("ready..")
    let isValid = checking(id)
    return isValid
}

let validationResult = validate(id: "User002", checking: checking)

let validationResult2 = validate(id: "User001", checking: {(id:String) in
    if id == "User000" {
        return false
    }
    return true
})
let printHello = {
    print("hello swift")
}

func doSomeClosure(_ action: () -> Void) {
    action()
}

doSomeClosure(printHello)

doSomeClosure({()->Void in
    print("hello swift")
})

헷갈렸던 point

{ (<#parameters#>) -> <#return type#> in
   <#statements#>
}

closure의 기본 형태는 다음과 같다. parameters에 괄호가 쳐진 걸 볼 수 있는데, 함수 파라미터로 사용할때에도 반드시 괄호를 쳐줘야 오류가 나지 않는다.

closure 줄여보기

  • 같은 동작을 하지만 줄여서 짧게 표현할 수 있다
let validationResult2 = validate(id: "User001", checking: { (id: String) in
    if id == "User000" {
          return false
      }

      return true
})

이렇게 긴 코드를 중간 단계로 줄이면 이렇게 표현할 수 있다

let validationResult3 = validate(id: "User001") { id in
    let isValid = id != "User000"
    return isValid
}

더 짧게 줄이면 이렇게 표현할 수 있다

let validationResult4 = validate(id: "User002") { $0 != "User000" }

해당 축약이 가능한 이유는 공식문서를 보면 알 수 있다

Swift’s closure expressions have a clean, clear style, with optimizations that encourage brief, clutter-free syntax in common scenarios. These optimizations include:

  • Inferring parameter and return value types from context
  • Implicit returns from single-expression closures
  • Shorthand argument names
  • Trailing closure syntax
  • Swift automatically provides shorthand argument names to inline closures, which can be used to refer to the values of the closure’s arguments by the names $0, $1, $2, and so on.

0개의 댓글