[swift] Objective-C와 Swift에서의 델리게이션 및 클로저 활용 방법의 차이

Objective-C 및 Swift 모두 iOS 및 macOS 앱 개발에 널리 사용되는 프로그래밍 언어입니다. 이들 언어는 델리게이션 및 클로저를 활용하여 각각의 특정 기능을 구현할 수 있습니다. 그러나 Objective-C와 Swift에서 델리게이션 및 클로저를 활용하는 방법은 약간의 차이가 있습니다.

델리게이션 사용하기

Objective-C에서는 델리게이션을 설정할 때 프로토콜을 사용하여 해당 델리게이트 메서드를 정의하고 구현합니다. Objective-C 코드에서는 다음과 같이 델리게이션을 설정할 수 있습니다.

// DelegateProtocol.h
@protocol DelegateProtocol
- (void)doSomething;
@end

// SomeClass.h
@interface SomeClass
@property (nonatomic, weak) id<DelegateProtocol> delegate;
@end

// SomeClass.m
@implementation SomeClass
- (void)performAction {
    [self.delegate doSomething];
}
@end

Swift에서는 프로토콜과 델리게이션을 사용하는 방법이 약간 다릅니다. Swift 코드에서는 다음과 같이 델리게이션을 설정할 수 있습니다.

// Protocol.swift
protocol DelegateProtocol: AnyObject {
    func doSomething()
}

// SomeClass.swift
class SomeClass {
    weak var delegate: DelegateProtocol?

    func performAction() {
        self.delegate?.doSomething()
    }
}

클로저 활용하기

Objective-C에서는 클로저를 사용하지 않습니다. 그러나 Swift에서는 클로저를 통해 특정 동작을 수행할 수 있습니다. 다음은 Swift에서 클로저를 활용하는 방법의 간단한 예시입니다.

// ClosureExample.swift
class ClosureExample {
    var closure: (() -> Void)?

    func performAction() {
        if let closure = self.closure {
            closure()
        }
    }
}

// ViewController.swift
class ViewController: UIViewController {
    let example = ClosureExample()

    override func viewDidLoad() {
        super.viewDidLoad()
        example.closure = {
            print("Closure executed")
        }
        example.performAction() // "Closure executed" 출력
    }
}

이와 같이 Objective-C와 Swift에서 각각의 문법과 기능적인 차이점이 존재하며, 고유의 특징을 가지고 있습니다.

델리게이션과 클로저는 Objective-C와 Swift에서 각각의 방식으로 활용될 수 있으며, 해당 언어의 특성을 살려 사용할 수 있습니다.

참고 자료

Objective-C와 Swift에서의 델리게이션 및 클로저 활용 방법의 차이에 대한 간단한 소개였습니다. 두 언어의 활용 방법을 이해하고 특정 상황에 맞게 적절히 활용할 수 있도록 노력해보세요.