Swift/Swift 문법

[클로저 - 3] 클로저 문법 최적화

내일은개발천재🎵 2022. 12. 28. 23:28

문법 최적화 원칙

  1. 문맥 상에서 파라미터와 리턴 값의 타입이 추론된다면 생략할 수 있다.
  2. 싱글 익스프레션의 경우 (코드가 한 줄) 리턴 키워드는 생략할 수 있다. (Implic return)
  3. 아규먼트 이름의 축약(Shorthand Arguments) → $0, $1로 표현
  4. 트레일링 클로저 문법
    • 함수의 마지막 전달 인자(아규먼트)로 클로저를 전달할 때, 소괄호를 생략할 수 있다.

트레일링 클로저, 후행 클로저 문법

  • 클로저가 실행될 때 적용할 수 있는 문법
  • 함수의 마지막 전달인자로 클로저가 전달되면, 소괄호를 생략할 수 있다.
    • 소괄호를 중괄호 앞으로 가져온다.
    • argument 생략 가능
    • 소괄호 생략 가능

예제 1

  1. closure의 정의 및 사용
func closureParamFunction(closure: () -> String) {
	closure()
}

2. 위 함수를 호출하는 방법 (마지막 argument == closure인 상황)

closureParamFunction(closure: {
	print("Hello World!")
})

// 후행 클로저 문법에 의해 소괄호를 생략할 수 있다.
closureParamFunction { print("Hello World!") }

예제2

func closureParamFunction(a: Int, b: Int, closure: (Int) -> Void) {
	let c = a + b
	closure(c)
}

closurePAramFunction(a: 5, b: 2) { number in
	print("result = \\(number)")
}

 

파라미터 및 생략 등의 간소화

  • 매개변수가 클로저인 함수 정의
func performClosure(param: (String) -> Int) { 
	param("Swift") 
}
  1. 타입추론
performClosure(param: { (str: String) in
	return str.count
}

performClosure(param: str in
	return str.count
}

 

2. Implict Return

performClosure(param: str in
	str.count
}
Implict Return 이란?
Swift 5.1부터 함수나 클로저의 코드가 한 줄일 때, return 키워드를 생략할 수 있는 것이다.

 

3. Shorthand Arguments (아규먼트 축약)

performClosure(param: { $0.count })

 

4. 후행 클로저 문법 (소괄호 생략)

performClosure() { $0.count }

 

예제

let closureType = { (param) in
	return param % 2 == 0
}

let closureType2 = { $0 % 2 == 0 }
let closureType = { (a: Int, b: Int) -> Int in
	return a * b
}

let closureType2: (Int, Int) -> Int = { (a, b) in
	a * b
}

let closureType3: (Int, Int) -> Int = { $0 * $1 }

Multiple Trailing Closure

  • Swift5.3부터 적용된 문법
  • 여러 개의 함수를 파라미터로 사용할 때 사용하는 문법이다.
func multipleClosure(first: () -> (), second: () -> (), third: () -> ()) {
    first()
    second()
    third()
}

// 예전 방법
multipleClosure(first: {
    print("1")
}, second: {
    print("2")
}) {
    print("3")
}

// 멀티플 트레일링 클로저
multipleClosure {
    print("mutil-1")
} second: {
    print("mutil-2")
} third: {
    print("mutil-3")
}
  • 예전 방법의 경우, 클로저의 경계에서 코드가 헷갈릴 가능성이 있었다.

예제 - SwiftUI의 버튼 작성방법

struct OldContentView: View {
    @State private var showOptions = false

    var body: some View {
        Button(action: {
            self.showOptions.toggle()
        }) {
            Image(systemName: "gear")
        }
    }
}

struct NewContentView: View {
    @State private var showOptions = false

    var body: some View {
        Button {
            self.showOptions.toggle()
        } label: {
            Image(systemName: "gear")
        }
    }
}

코드 츨처 | hacking with Swift


프로젝트 적용

1. 후행클로저 문법 적용 sugestion

 

[Feat] 다른 사용자 프로필 화면 구현 by jim4020key · Pull Request #343 · DeveloperAcademy-POSTECH/MacC-Team-HappyAn

관련 이슈 closes #308 구현/변경 사항 단축어 상세 화면, 큐레이션 상세 화면에서 닉네임 클릭시 넘어가는 프로필 화면을 구현했습니다. CurationCell은 bottom에 패딩이 있고, ShortcutCell은 top에 패딩이

github.com

 

2. (Implict Return)

 

[Feat] 버전 업데이트 알림창 by JMM00 · Pull Request #341 · DeveloperAcademy-POSTECH/MacC-Team-HappyAnding

관련 이슈 closes #312 구현/변경 사항 로그인 정보를 검사하는 곳을 최상단에서 ShortcutsZipView(새로 생성) 으로 변경 파이어스토어에 Version 도큐먼트 생성 위의 도큐먼트에서 minimum_version값과 현재

github.com


이 글은 앨런님의 강의를 듣고 작성한 글입니다