Skip to content

Instantly share code, notes, and snippets.

private var tokenPub: AnyPublisher<String, Error>? // make this private to prevent unintended direct access to this publisher … you want to make sure that all access is via your private queue
private let tokenPubQueue = DispatchQueue( // make this `private`, as it is internal to this type
label: Bundle.main.bundleIdentifier! + ".tokenQueue"
)
func accessToken(refreshToken: String) -> AnyPublisher<String, Error> {
return tokenPubQueue.sync {
if let tokenPub {
return tokenPub
}
class ImageManager {
func downloadInOrderIndependentDictionary() async throws -> [String: Image] {
try await withThrowingTaskGroup(of: (String, Image?).self) { group in
let items = await fetchList()
for item in items {
group.addTask {
do {
return try await (item.imageName, self.fetch(imageName: item.imageName))
} catch is CancellationError {
// modern syntax of `NSRegularExpression`
func splitedString(string: String, length: Int) -> [String] {
let regexString = "(\\d{1,\(length)})"
let nsstring = string as NSString
let regex = try! NSRegularExpression(pattern: regexString)
return regex
.matches(in: string, range: NSRange(string.startIndex..., in: string))
.map { nsstring.substring(with: $0.range) }
extension StringProtocol {
func split(into length: Int) -> [SubSequence] {
let count = self.count
return stride(from: 0, to: count, by: length).map { i in
let start = index(startIndex, offsetBy: i)
let end = index(startIndex, offsetBy: Swift.min(i + length, count))
return self[start ..< end]
}
}
/// Find `Counter` with particular `number`
///
/// This uses `async` from [Swift async algorithms](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/Lazy.md)
/// to make an `AsyncSequence` from the `counters` collection.
func getCounter3(number: Int) async -> Counter? {
await counters.async.first { counter in
await counter.number == number
}
}
extension Sequence {
func first(where predicate: sending (Self.Element) async throws -> Bool) async rethrows -> Self.Element? {
for element in self {
if try await predicate(element) {
return element
}
}
return nil
}
}
final class MyAppTests: XCTestCase {
var cancellables: Set<AnyCancellable> = []
func testDemoDataIncorrect() {
let start = Date.now
// fire an event in 1 second, but only get the first value
let publisher = Timer.publish(every: 1, on: .main, in: .default)
.autoconnect()
func upload(files: [URL]) async throws -> Bool {
try await withThrowingTaskGroup(of: Bool.self) { group in
let session = try SSH(host: "xxx", port:"xxx")
let sftp = try session.openSftp()
for file in files {
group.addTask {
try await self.upload(file: file, with: sftp, session: session)
}
}
func dummyLoop() async throws {
print("inside dummy fcn")
for i in 0 ..< 10 {
print("Loop \(i)")
try await Task.sleep(for: .seconds(1))
}
}
enum MyError: Error {
case one
case two
}
actor Example {
func funcWithTypedThrow() async throws(MyError) { throw .one }
// OK