iOS

iOS (Swift) Closure 의 개념과 사용 방법

crazydeer 2022. 6. 23. 09:00
반응형

일반적인 함수의 형태는 아래와 같다.

func functionName (param1: dataType, param2: dataType) -> dataType {
  return output
}

 

특정 데이터가 입력되어 함수를 통과하면

데이터가 출력된다.

 입력된 데이터들을  다른 함수를 통과하도록   있다.

 

import UIKit
import Foundation


func calculator(n1: Int, n2: Int, operation: (Int, Int) -> Int) -> Int{
    return operation(n1, n2)
}


func add(n1: Int, n2: Int) -> Int{
    return n1 + n2
}


print(calculator(n1: 2, n2: 3, operation: add(n1:n2:)))
//결과: 5

 

 

Closure 함수명을 지우고 중괄호( { ) 제일 앞으로 옮기고

 자리에 in 써주고 그대로 써준다.

말로는 설명이 힘드니 코드를 바로 보자.

 

import UIKit
import. Foundation


func calculator(n1: Int, n2: Int, operation: (Int, Int) -> Int) -> Int{
    return operation(n1, n2)
}


func add(n1: Int, n2: Int) -> Int{
    return n1 + n2
}


calculator(n1: 2, n2: 3, operation: { (n1: Int, n2: Int) -> Intin return n1 * n2 })


//결과: 6

 

 

 코드의 마지막 줄을  줄일 수도 있다.

 

calculator(n1: 2, n2: 3, operation: { (n1, n2) in n1 * n2 })

 

컴파일 시에 스위프트는 n1 n2 그리고 output 데이터 타입까지

추론할  있다.

심지어 뒷부분의 n1 n2까지도 생략할  있다.

 

import UIKit
import Foundation


func calculator(n1: Int, n2: Int, operation: (Int, Int) -> Int) -> Int{
    return operation(n1, n2)
}


func add(n1: Int, n2: Int) -> Int{
    return n1 + n2
}


let result = calculator(n1: 2, n2: 3, operation: { $0 * $1 })
print(result)


// 결과: 6

 

이렇게 똑같이  동작한다.

 

 

마지막으로  생략할  있다.

 

let result= calculator(n1: 2, n2: 3) { $0 * $1 }

 

이렇게 해도 똑같이 동작한다.

이렇게 { 받은 변수 + 수식 } 으로  수도 있다.

이를 Tailing Closure라고 한다.

 

이렇게 줄이는 코드를 좋다고 하는 개발자도 있지만

풀어서 함수를 만들고  함수를 갖다 쓰는게

해석하기에  좋은 코드라고 하는 개발자도 있다.

 

// 방법 1
let result= calculator(n1: 2, n2: 3) { $0 * $1 }
print(result)


// 방법 2
func multiply(no1: Int, no2: Int) -> Int{
    return no1 * no2
}
print(calculator(n1: 2, n2: 3, operation: multiply))

 

나는 개인적으로 방법 2 좋은데

여러가지  알고 있어야 다른 사람의 코드를 해석할  있을  같다.

어떤 식으로 코딩할지는 프로그래머 마음이다.

 

 

 

Array에 적용해보기

 

Apple Developer Documentation

 

developer.apple.com

 

위 링크 사이트

 

let array= [6,2,3,9,4,1]


func addOne(n1: Int) -> Int{
    return n1 + 1
}


array.map(addOne)


// [7, 3, 4, 10, 5, 2]

 

이렇게 map 통해 배열의 모든 요소들에 1 더해줄  있다.

이걸 클로저를 사용해서 줄여보자.

 

먼저 func addOne을 지워준다.

그 다음 오른쪽에 남아있는 {  제일 앞으로 옮겨준다.

{ (n1: Int) -> Int 
    return n1 + 1
}

 

그 다음 Int 오른쪽에 in 키워드를 추가해준다.

그리고 addOne 대신 써준다.

let array= [6,2,3,9,4,1]


array.map({ (n1: Int) -> Intin
    return n1 + 1
})

 

입력값의 데이터 타입과

출력값의 데이터 타입도 생략한다.

let array= [6,2,3,9,4,1]


array.map({ (n1) in return n1 + 1})

 

return 까지 생략 가능

let array= [6,2,3,9,4,1]


array.map({ (n1) in n1 + 1 })

 

그리고 아예  지우고 인풋 파라미터를 받는 $ 기호를 사용하여

간결화한다.

let array= [6,2,3,9,4,1]


array.map{$0 + 1}

 

 

 

예시 코드

let array= [6,2,3,9,4,1]


let addArray= array.map{$0 + 1}
print(addArray)


let newArray= array.map{"\($0)"}
print(newArray)

 

 

결과

위 코드 실행 결과

 

 

Closure 표현 구문

 

Closures — The Swift Programming Language (Swift 5.7)

Closures Closures are self-contained blocks of functionality that can be passed around and used in your code. Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages. Closures can capture and store referen

docs.swift.org

 

클로저(Closure) 기본 구문 구조

 

 

참고

안젤라유 강의: https://www.udemy.com/course/ios-13-app-development-bootcamp/

 

iOS & Swift - The Complete iOS App Development Bootcamp

From Beginner to iOS App Developer with Just One Course! Fully Updated with a Comprehensive Module Dedicated to SwiftUI!

www.udemy.com

 

반응형