Skip to content

Instantly share code, notes, and snippets.

@iharkatkavets
Created March 30, 2026 19:22
Show Gist options
  • Select an option

  • Save iharkatkavets/cf5c5fb690b0cf705cd2364e6eacb811 to your computer and use it in GitHub Desktop.

Select an option

Save iharkatkavets/cf5c5fb690b0cf705cd2364e6eacb811 to your computer and use it in GitHub Desktop.
1114. Print in Order (Swift version)
import Foundation
import Synchronization
// The problem repeats the LC problem '1114. Print in Order'
// https://leetcode.com/problems/print-in-order
// Implement your solution inside the `Foo` class.
// Test with: swift main.swift
final class Foo: Sendable {
init() {
}
func first(_ printFirst: @escaping @Sendable () async -> Void) async {
await printFirst() // Don't change this line
}
func second(_ printSecond: @escaping @Sendable () async -> Void) async {
await printSecond() // Don't change this line
}
func third(_ printThird: @escaping @Sendable () async -> Void) async {
await printThird() // Don't change this line
}
}
// MARK: -
// This section is required for the problem testing.
// Do not modify.
for _ in 0..<10_000 {
await runSolution()
}
func runSolution() async {
actor Context {
var str = ""
func add(_ suffix: String) {
str += suffix
}
}
let result = await withTaskGroup(of: Void.self) { group in
let foo = Foo()
let result = Context()
for i in [2, 1, 0] {
group.addTask {
switch i {
case 0:
await foo.first {
await result.add("first")
}
case 1:
await foo.second {
await result.add("second")
}
case 2:
await foo.third {
await result.add("third")
}
default:
break
}
}
}
await group.waitForAll()
return await result.str
}
assert(result == "firstsecondthird", "\"\(result)\" != \"firstsecondthird\"")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment