카테고리 없음
[Swift] 기존 비동기 코드를 Async, Await으로 쉽게 변경하기
윈컴이
2022. 12. 6. 01:50
func getImage(completion: @escaping (UIImage?) -> Void) {
// 이미지를 가져오는 코드
completion(nil)
}
getImage { [weak self] image in
self?.artworkImageView.image = image
}
위와 같은 코드가 있다고 생각해봅시다. 이 코드를 하위호환성을 유지하면서 Async, Await도 사용하기 위해 어떤 식으로 코드를 작성해야할까요? 해답은 Xcode의 Refactor에 있었습니다.
Add Async Wrapper를 선택하게 되면 위의 코드를 아래와 같이 변경해줍니다.
@available(*, renamed: "getImage()")
func getImage(completion: @escaping (UIImage?) -> Void) {
completion(nil)
}
func getImage() async -> UIImage? {
return await withCheckedContinuation { continuation in
getImage() { result in
continuation.resume(returning: result)
}
}
}
// 사용
let image: UIImage? = await getImage()
앞으로 더 편하게 Async, Await 코드로 변경할 수 있게 되었습니다! 만약 Add Async Alternative를 선택할 경우 아래와 같이 나타납니다.
@available(*, renamed: "getImage()")
func getImage(completion: @escaping (UIImage?) -> Void) {
Task {
let result = await getImage()
completion(result)
}
}
func getImage() async -> UIImage? {
return nil
}