Skip to content

Instantly share code, notes, and snippets.

@ulkomar
Created June 19, 2023 11:55
Show Gist options
  • Save ulkomar/c08bb65ac1fa01de1c3508587d6a1f51 to your computer and use it in GitHub Desktop.
Save ulkomar/c08bb65ac1fa01de1c3508587d6a1f51 to your computer and use it in GitHub Desktop.
import Foundation
enum FeedItemType {
case text
case photo
case video
}
struct FeedItem {
let id: UUID
let type: FeedItemType
}
struct TextModel {
let text: String
}
struct PhotoModel {
let imageURL: URL
}
struct VideoModel {
let videoURL: URL
let duration: Double
}
enum CommonFeedType {
case text(TextModel)
case photo(PhotoModel)
case video(VideoModel)
}
var feedItems: [FeedItem] = [
.init(id: UUID(uuidString: "1")!, type: .photo),
.init(id: UUID(uuidString: "2")!, type: .text),
.init(id: UUID(uuidString: "3")!, type: .video)
]
func getAllPosts() async throws -> [CommonFeedType] {
let funcResult = try await withThrowingTaskGroup(of: CommonFeedType.self) { group in
for item in feedItems {
switch item {
case .text:
let textItemReponse = try await fetchTextItem(withID: item.id)
return CommonFeedType.text(textItemReponse)
case .photo:
let photoItemReponse = try await fetchPhotoItem(withID: item.id)
return CommonFeedType.text(photoItemReponse)
case .video:
let videoItemReponse = try await fetchVideoItem(withID: item.id)
return CommonFeedType.text(videoItemReponse)
}
}
var results = [CommonFeedType]()
while let result = await group.nextResult() {
do {
let item = try result.get()
results.append(item)
} catch {
// handle error
}
}
return results
}
return funcResult
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment