Spaces:
Paused
Paused
File size: 4,406 Bytes
93d826e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 | import Foundation
// Protocol definitions
protocol DataProcessor {
associatedtype Input
associatedtype Output
func process(_ input: Input) async throws -> Output
func validate(_ input: Input) -> Bool
}
// Error type
enum ProcessingError: LocalizedError {
case invalidInput(String)
case processingFailed(String)
var errorDescription: String? {
switch self {
case .invalidInput(let reason): return "Invalid input: \(reason)"
case .processingFailed(let reason): return "Processing failed: \(reason)"
}
}
}
// Property wrapper
@propertyWrapper
struct Validated<T> {
private var value: T
private let validator: (T) -> Bool
var wrappedValue: T {
get { value }
set {
guard validator(newValue) else {
fatalError("Invalid value")
}
value = newValue
}
}
init(wrappedValue: T, validator: @escaping (T) -> Bool) {
guard validator(wrappedValue) else {
fatalError("Invalid initial value")
}
self.value = wrappedValue
self.validator = validator
}
}
// Actor for thread-safe state management
actor ProcessingState {
private(set) var processedCount: Int = 0
private var status: Status = .pending
enum Status {
case pending
case processing
case completed
case failed(Error)
}
func incrementCount() {
processedCount += 1
}
func updateStatus(_ newStatus: Status) {
status = newStatus
}
}
// Generic struct with where clause
struct Queue<Element> where Element: Sendable {
private var elements: [Element] = []
private let lock = NSLock()
mutating func enqueue(_ element: Element) {
lock.lock()
defer { lock.unlock() }
elements.append(element)
}
mutating func dequeue() -> Element? {
lock.lock()
defer { lock.unlock() }
return elements.isEmpty ? nil : elements.removeFirst()
}
}
// Class inheritance and protocol conformance
class StringProcessor: DataProcessor {
typealias Input = String
typealias Output = String
private let state = ProcessingState()
@Validated(validator: { !$0.isEmpty })
private var currentInput: String = "default"
func process(_ input: String) async throws -> String {
guard validate(input) else {
throw ProcessingError.invalidInput("String is empty")
}
await state.updateStatus(.processing)
// Simulate processing
try await Task.sleep(nanoseconds: 1_000_000_000)
let result = input.uppercased()
await state.incrementCount()
await state.updateStatus(.completed)
return result
}
func validate(_ input: String) -> Bool {
!input.isEmpty
}
}
// Extension with async sequence
extension StringProcessor: AsyncSequence, AsyncIteratorProtocol {
typealias Element = String
func makeAsyncIterator() -> StringProcessor {
self
}
func next() async throws -> String? {
try await process(currentInput)
}
}
// Result builders
@resultBuilder
struct ArrayBuilder<T> {
static func buildBlock(_ components: T...) -> [T] {
components
}
}
// Function using result builder
func makeArray<T>(@ArrayBuilder<T> content: () -> [T]) -> [T] {
content()
}
// Async main function demonstrating usage
@main
struct Example {
static func main() async throws {
let processor = StringProcessor()
var queue = Queue<String>()
// Using result builder
let inputs = makeArray {
"Hello"
"World"
"Swift"
}
// Process inputs
for input in inputs {
queue.enqueue(input)
}
// Process queue
while let input = queue.dequeue() {
do {
let result = try await processor.process(input)
print("Processed: \(result)")
} catch {
print("Error: \(error.localizedDescription)")
}
}
// Using async sequence
for try await result in processor.prefix(3) {
print("Async sequence result: \(result)")
}
}
}
|