Skip to content

Instantly share code, notes, and snippets.

@profh
Created October 29, 2024 01:13
Show Gist options
  • Save profh/a2d6bbab48c8ee741eb7692646d529b5 to your computer and use it in GitHub Desktop.
Save profh/a2d6bbab48c8ee741eb7692646d529b5 to your computer and use it in GitHub Desktop.
Repos_Async_Part_2
import SwiftUI
import Foundation
struct Repository: Decodable {
let name: String
let htmlURL: String
enum CodingKeys : String, CodingKey {
case name
case htmlURL = "html_url"
}
}
struct Repositories: Decodable {
let data: [Repository]
enum CodingKeys : String, CodingKey {
case data = "items"
}
}
// MARK: Extend Repositories to add the fecthRepositories method
extension Repositories {
static func fetchRepositories() async throws -> [Repository] {
let url = URL(string: "https://api.github.com/search/repositories?q=language:swift&sort=stars&order=desc")!
let (data, _) = try await URLSession.shared.data(from: url)
return try JSONDecoder().decode(Repositories.self, from: data).data
}
}
// MARK: Extend Repositories with a getter
extension Repositories {
static var repos: [Repository] {
get async throws {
try await fetchRepositories()
}
}
}
// MARK: Extend Repositories with subscript to get a specific repo
enum Error: Swift.Error { case outOfRange } // for now, just concerned about one error
extension Repositories {
static subscript(_ index: Int) -> Repository {
get async throws {
let repos = try await Self.repos
guard repos.indices.contains(index) else {
throw Error.outOfRange
}
return repos[index]
}
}
}
// --------------
// Now to get the repos async, it's as easy as:
Task {
do {
for repo in try await Repositories.repos {
print(" - \(repo.name): \(repo.htmlURL)")
}
} catch {
print(error)
}
}
// --------------
// And if I wanted just one repo, it'd be:
Task {
// let repo = try await Repositories[19]
// print("\(repo.name)")
do {
dump(try await Repositories[19].name) // Dumps the given object’s contents.
}
// catch { // since really only one type of error...
catch Error.outOfRange {
print("Index out of range")
}
catch {
print("Who the heck knows?")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment