Swift Functions and Closures


함수의 정의와 호출 (Defining and Calling Functions)

함수 정의 (Defining Functions)

함수는 특정 작업을 수행하는 코드 블록입니다. func 키워드를 사용하여 함수를 정의합니다.

func greet() {
    print("Hello, World!")
}

함수 호출 (Calling Functions)

정의된 함수를 호출하여 실행합니다.

greet()  // "Hello, World!"

함수의 매개변수와 반환 값 (Function Parameters and Return Values)

매개변수 (Parameters)

함수는 매개변수를 통해 값을 전달받아 사용할 수 있습니다. 매개변수는 함수 이름 뒤에 괄호 안에 정의합니다.

func greet(name: String) {
    print("Hello, \(name)!")
}

greet(name: "Alice")  // "Hello, Alice!"

반환 값 (Return Values)

함수는 반환 값을 가질 수 있으며, -> 키워드를 사용하여 반환 타입을 명시합니다.

func add(a: Int, b: Int) -> Int {
    return a + b
}

let sum = add(a: 3, b: 5)
print(sum)  // 8

여러 매개변수와 반환 값 (Multiple Parameters and Return Values)

여러 매개변수를 가지는 함수와 여러 개의 값을 반환하는 함수도 정의할 수 있습니다.

func multiplyAndDivide(a: Int, b: Int) -> (product: Int, quotient: Int) {
    let product = a * b
    let quotient = a / b
    return (product, quotient)
}

let result = multiplyAndDivide(a: 6, b: 2)
print("Product: \(result.product), Quotient: \(result.quotient)")
// "Product: 12, Quotient: 3"

매개변수 기본값 (Default Parameter Values)

매개변수에 기본값을 지정할 수 있습니다.

func greet(name: String = "Guest") {
    print("Hello, \(name)!")
}

greet()          // "Hello, Guest!"
greet(name: "Bob")  // "Hello, Bob!"

가변 매개변수 (Variadic Parameters)

가변 매개변수는 여러 개의 값을 받을 수 있습니다.

func sum(of numbers: Int...) -> Int {
    var total = 0
    for number in numbers {
        total += number
    }
    return total
}

print(sum(of: 1, 2, 3, 4, 5))  // 15

클로저의 개념과 활용 (Closures in Swift)

클로저의 개념 (Understanding Closures)

클로저는 코드 블록을 캡처하고 전달할 수 있는 기능을 제공합니다. 클로저는 일반적으로 함수나 메서드에서 인라인으로 사용됩니다.

let greetingClosure = {
    print("Hello, World!")
}

greetingClosure()  // "Hello, World!"

클로저 표현식 (Closure Expressions)

클로저 표현식을 사용하여 클로저를 더 간결하게 작성할 수 있습니다.

let sumClosure: (Int, Int) -> Int = { (a: Int, b: Int) in
    return a + b
}

let result = sumClosure(3, 5)
print(result)  // 8

클로저의 간략화 (Simplifying Closures)

Swift는 클로저를 간략화할 수 있는 여러 가지 문법을 제공합니다.

  1. 매개변수 및 반환 타입 유추 (Inferring Parameter and Return Types) let multiplyClosure = { (a, b) in a * b } let product = multiplyClosure(3, 5) print(product) // 15
  2. 단축 인자 이름 (Shorthand Argument Names) let subtractClosure: (Int, Int) -> Int = { $0 - $1 } let difference = subtractClosure(10, 3) print(difference) // 7
  3. 후행 클로저 (Trailing Closures) 후행 클로저는 함수의 마지막 매개변수로 클로저를 전달할 때 사용합니다. func performOperation(a: Int, b: Int, operation: (Int, Int) -> Int) -> Int { return operation(a, b) } let result = performOperation(a: 10, b: 5) { $0 * $1 } print(result) // 50

클로저의 활용 (Using Closures)

클로저는 콜백 함수로 많이 사용됩니다. 예를 들어, 배열의 정렬에 사용할 수 있습니다.

let names = ["Charlie", "Alice", "Bob"]
let sortedNames = names.sorted { $0 < $1 }
print(sortedNames)  // ["Alice", "Bob", "Charlie"]

클로저는 비동기 작업에서도 자주 사용됩니다. 예를 들어, 네트워크 요청의 완료 핸들러로 사용할 수 있습니다.

func fetchData(completion: @escaping (String) -> Void) {
    // 비동기 작업 시뮬레이션
    DispatchQueue.global().async {
        let data = "Fetched Data"
        DispatchQueue.main.async {
            completion(data)
        }
    }
}

fetchData { data in
    print(data)  // "Fetched Data"
}

이와 같이 Swift에서 함수와 클로저는 매우 강력하고 유연한 기능을 제공합니다. 함수의 정의와 호출, 매개변수와 반환 값, 그리고 클로저의 개념과 활용에 대한 예제를 통해 기본적인 사용법을 이해할 수 있습니다.


Leave a Reply

Your email address will not be published. Required fields are marked *