[swift] PromiseKit에서의 델리게이션 패턴 활용 방법

PromiseKit은 iOS 애플리케이션 개발을 위한 인기있는 프로미스 라이브러리입니다. 프로미스를 사용하면 비동기 작업을 보다 간편하고 선언적인 방식으로 처리할 수 있습니다. 이번 글에서는 PromiseKit에서 델리게이션 패턴을 활용하는 방법에 대해 알아보겠습니다.

1. 델리게이션 패턴 소개

델리게이션 패턴은 객체 간의 통신을 위해 자주 사용되는 디자인 패턴입니다. 하나의 객체가 다른 객체를 대신하여 특정 동작을 수행하도록 위임하는 것을 의미합니다. 이를 통해 객체들 간의 결합도를 낮추고 유연성을 높일 수 있습니다.

2. PromiseKit에서의 델리게이션 패턴 활용

PromiseKit에서는 비동기 작업이 완료되었을 때 처리해야 하는 로직을 델리게이션 패턴을 통해 처리할 수 있습니다. 아래는 PromiseKit에서 델리게이션 패턴을 활용한 예제 코드입니다.

import PromiseKit

protocol ImageDownloaderDelegate: AnyObject {
    func didDownloadImage(image: UIImage)
    func didFailWithError(error: Error)
}

class ImageDownloader {
    weak var delegate: ImageDownloaderDelegate?
    
    func downloadImage(url: URL) {
        firstly {
            URLSession.shared.dataTask(.promise, with: url)
        }.compactMap { data, _ in
            UIImage(data: data)
        }.done { image in
            self.delegate?.didDownloadImage(image: image)
        }.catch { error in
            self.delegate?.didFailWithError(error: error)
        }
    }
}

class ImageViewController: UIViewController, ImageDownloaderDelegate {
    let imageDownloader = ImageDownloader()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        imageDownloader.delegate = self
        
        // 이미지 다운로드 시작
        let imageUrl = URL(string: "https://example.com/image.jpg")!
        imageDownloader.downloadImage(url: imageUrl)
    }
    
    func didDownloadImage(image: UIImage) {
        // 다운로드 완료 후 이미지 처리 로직
    }
    
    func didFailWithError(error: Error) {
        // 에러 처리 로직
    }
}

위 예제 코드에서 ImageDownloader 클래스는 이미지를 다운로드하는 역할을 합니다. 다운로드가 완료되면 델리게이트에게 이미지를 전달하거나 에러를 전달합니다. ImageViewController 클래스에서는 ImageDownloader의 델리게이트로 동작하며, 이미지 다운로드가 완료되거나 에러가 발생했을 때 적절한 로직을 수행합니다.

3. 결론

델리게이션 패턴은 PromiseKit을 활용하여 비동기 작업을 처리하는데 유용한 방법입니다. 객체 간의 결합도를 낮추고 유연성을 높일 수 있는 이 패턴은 코드의 가독성과 재사용성을 향상시킬 수 있습니다. 앞으로 PromiseKit을 사용할 때, 델리게이션 패턴을 적절히 활용해 보세요.