[swift] 비동기 작업간의 데이터 전달 방법

비동기 작업을 수행하는 동안 데이터를 전달하는 방법은 필요한 경우 매우 중요합니다. 여러 가지 방법을 사용하여 데이터를 전달할 수 있지만, 가장 널리 사용되는 방법은 completion handlerclosure를 사용하는 것입니다. 그 외에도 Notification이나 Delegate를 활용할 수도 있습니다.

Completion Handler를 활용한 데이터 전달

Completion handler는 비동기 작업이 완료되었을 때 해당 작업의 결과나 데이터를 전달하는 데 사용됩니다. 대표적인 예시로는 네트워크 호출이나 파일 다운로드 등이 있습니다.

func fetchData(completion: @escaping (Result<Data, Error>) -> Void) {
    // 비동기 작업 수행
    // 작업 완료 후
    if success {
        completion(.success(data))
    } else {
        completion(.failure(error))
    }
}

fetchData { result in
    switch result {
    case .success(let data):
        // 데이터 활용
    case .failure(let error):
        // 에러 처리
    }
}

위 예시에서 fetchData 함수는 completion 클로저를 매개변수로 받아 작업이 완료되면 해당 클로저에 결과를 전달합니다.

Notification 활용

Notification은 여러 객체에 데이터를 전달할 때 유용한 방법입니다. 일반적으로 한 객체에서 발생한 이벤트나 변화를 다른 객체에 통지할 때 사용됩니다.

// 데이터 전달
let data = ["key": value]
NotificationCenter.default.post(name: Notification.Name("DataNotification"), object: nil, userInfo: data)

// 데이터 수신
let observer = NotificationCenter.default.addObserver(forName: Notification.Name("DataNotification"), object: nil, queue: nil) { notification in
    if let data = notification.userInfo {
        // 데이터 활용
    }
}

위 코드에서는 NotificationCenter를 사용하여 데이터를 전달하고, addObserver를 통해 해당 데이터를 수신하는 방법을 보여줍니다.

Delegate 활용

Delegate는 한 객체가 다른 객체에 대한 동작을 위임하는 패턴으로, 데이터를 전달하는 데 널리 사용됩니다. 보통 프로토콜을 정의하고 해당 프로토콜을 준수하는 객체가 데이터를 전달하는 방식입니다.

protocol DataDelegate: AnyObject {
    func didReceiveData(_ data: Any)
}

class DataManager {
    weak var delegate: DataDelegate?

    func fetchData() {
        // 데이터를 가져왔을 때
        delegate?.didReceiveData(data)
    }
}

class ViewController: DataDelegate {
    let dataManager = DataManager()

    init() {
        dataManager.delegate = self
    }

    func didReceiveData(_ data: Any) {
        // 데이터 활용
    }
}

위 예시는 Delegate를 활용하여 데이터를 전달하는 방법을 보여줍니다. DataManager 클래스는 DataDelegate 프로토콜을 채택하고 있는 ViewController 객체에 데이터를 전달합니다.

결론

비동기 작업 간의 데이터 전달은 Completion Handler, Notification, 그리고 Delegate를 활용하여 수행할 수 있습니다. 각 방법은 다양한 상황에 적합하며, 상황에 맞게 적절한 방법을 선택하여 사용해야 합니다.

참고 자료: