Skip to content

Instantly share code, notes, and snippets.

@jacobsapps
Created January 14, 2026 14:52
Show Gist options
  • Select an option

  • Save jacobsapps/5ce77991e3c6f289134a638361f9f3f5 to your computer and use it in GitHub Desktop.

Select an option

Save jacobsapps/5ce77991e3c6f289134a638361f9f3f5 to your computer and use it in GitHub Desktop.
protocol Problem1 {
func download()
}
private let imageURLs: [URL] = [
URL(string: "https://picsum.photos/seed/lorempixum1/400/300")!,
URL(string: "https://picsum.photos/seed/lorempixum2/400/300")!,
URL(string: "https://picsum.photos/seed/lorempixum3/400/300")!,
URL(string: "https://picsum.photos/seed/lorempixum4/400/300")!,
URL(string: "https://picsum.photos/seed/lorempixum5/400/300")!,
URL(string: "https://picsum.photos/seed/lorempixum6/400/300")!,
URL(string: "https://picsum.photos/seed/lorempixum7/400/300")!,
URL(string: "https://picsum.photos/seed/lorempixum8/400/300")!,
URL(string: "https://picsum.photos/seed/lorempixum9/400/300")!,
URL(string: "https://picsum.photos/seed/lorempixum10/400/300")!
]
final class Problem1GCD: Problem1 {
func download() {
// TODO:
// Download all images in `imageURLs`.
// Constraint: at no point may more than TWO downloads be executing concurrently.
// When all downloads are complete:
// - Switch to the main thread
// - Print "All downloads finished"
//
// Hint: consider `DispatchSemaphore` + `DispatchGroup`.
print("Problem1: TODO")
let group = DispatchGroup()
let semaphore = DispatchSemaphore(value: 2)
for image in imageURLs {
group.enter()
DispatchQueue.global(qos: .utility).async { [weak self] in
semaphore.wait()
self?.downloadImage(url: image) {
semaphore.signal()
group.leave()
}
}
}
group.notify(queue: .main) {
print("All downloads finished")
}
}
private func downloadImage(url: URL, _ completion: @escaping () -> Void) {
DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + 0.3) {
URLSession.shared.dataTask(with: url) { data, _, _ in
DispatchQueue.main.async {
print("Download finished for \(url.path)")
completion()
}
}.resume()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment