Created
March 30, 2026 19:22
-
-
Save iharkatkavets/cf5c5fb690b0cf705cd2364e6eacb811 to your computer and use it in GitHub Desktop.
1114. Print in Order (Swift version)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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