https://developer.apple.com/documentation/combine/future
Future | Apple Developer Documentation
A publisher that eventually produces a single value and then finishes or fails.
developer.apple.com
🚀 Future란? (초보자를 위한 쉬운 설명)
Future는 한 번만 데이터를 방출(emit)하는 Combine의 Publisher.
즉, 비동기 작업을 수행하고 결과(성공 or 실패)를 한 번만 전달한 후 종료하는 역할
💡 예제:
- 네트워크 요청 후 응답을 받으면 결과를 반환
- 비동기 작업(예: 파일 다운로드, 인증 처리 등) 후 단 한 번만 값을 반환
📌 Future는 언제 써?
✅ 어떤 비동기 작업이 있는데, 그 결과를 한 번만 전달하고 싶을 때
✅ 비동기 API(Firebase, URLSession 등)를 Combine과 함께 사용하고 싶을 때
📌 Future 사용법
Future를 사용하면 비동기 작업의 결과를 Publisher로 변환
아래 예제는 2초 후에 랜덤 숫자를 생성하는 Future
import Combine
func generateAsyncRandomNumber() -> Future<Int, Never> {
return Future { promise in
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
let number = Int.random(in: 1...10)
promise(.success(number)) // 결과 전달 후 Future 종료
}
}
}
✅ .success(value) → 성공한 값을 전달
✅ .failure(error) → 실패했을 때 에러 전달
📌 Future 값을 받는 방법
Combine에서는 sink를 사용해서 Future의 값을 받을 수 있어.
var cancellable = generateAsyncRandomNumber()
.sink { number in
print("🎲 랜덤 숫자: \(number)")
}
📝 출력 (2초 후)
🎲 랜덤 숫자: 7
📌 Future vs Swift의 async-await
이제 Swift 5.5 이상에서는 async-await을 사용할 수 있음
Future를 사용하지 않고 async-await을 사용하면 이렇게 돼:
func generateAsyncRandomNumber() async -> Int {
return await withCheckedContinuation { continuation in
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
let number = Int.random(in: 1...10)
continuation.resume(returning: number)
}
}
}
// Future 대신 async-await 사용
let number = await generateAsyncRandomNumber()
print("🎲 랜덤 숫자: \(number)")
✅ Future는 Combine에서 사용하는 방식 ✅
https://explorer89.tistory.com/362
🤔 Combine에서 Future를 사용하는 이유
https://explorer89.tistory.com/361 🤔 Future란? (Combine의 비동기 처리)https://developer.apple.com/documentation/combine/future Future | Apple Developer DocumentationA publisher that eventually produces a single value and then finishes or fails.
explorer89.tistory.com
✅ async-await은 Swift의 최신 방식
💡 Future는 Combine을 쓰는 프로젝트에서 주로 사용되고, 최신 프로젝트에서는 async-await이 더 간결할 수 있음! 🚀
'UIKIT > 비동기' 카테고리의 다른 글
🤔 Completion Handler를 Combine으로 변경할 때 고려해야 할 점? (0) | 2025.03.12 |
---|---|
🤔 Combine에서 Future를 사용하는 이유 (0) | 2025.02.26 |