🎯 Exemples recommandés
Balanced sample collections from various categories for you to explore
Exemples Swift
Exemples de code Swift essentiels pour le développement iOS, incluant les fonctionnalités modernes de Swift et SwiftUI
💻 Hello World Swift swift
🟢 simple
⭐⭐
Programme Hello World de base avec syntaxe moderne Swift et concepts de développement iOS
⏱️ 15 min
🏷️ swift, ios, functional programming
Prerequisites:
Basic programming concepts
// Swift Hello World Examples
import Foundation
// 1. Basic Hello World
print("Hello, World!")
// 2. Hello World with variable
let message = "Hello, World!"
print(message)
// 3. Hello World with function
func sayHello() -> String {
return "Hello, World!"
}
print(sayHello())
// 4. Hello World with parameters
func greet(_ name: String) -> String {
return "Hello, \(name)!"
}
print(greet("World"))
print(greet("Swift"))
// 5. Hello World with class
class Greeter {
private let message: String
init(message: String = "Hello, World!") {
self.message = message
}
func greet() {
print(message)
}
}
let greeter = Greeter()
greeter.greet()
// 6. Hello World with user input
func greetUser() {
print("Enter your name:")
if let name = readLine() {
print("Hello, \(name)!")
}
}
// greetUser()
// 7. Hello World multiple times
for i in 1...5 {
print("Hello, World! \(i)")
}
// 8. Hello World with array
let greetings = ["Hello", "Bonjour", "Hola", "Ciao", "こんにちは"]
for greeting in greetings {
print("\(greeting), World!")
}
// 9. Hello World with dictionary
let greetings: [String: String] = [
"en": "Hello",
"es": "Hola",
"fr": "Bonjour",
"de": "Hallo",
"ja": "こんにちは"
]
for (lang, greeting) in greetings {
print("\(greeting), World! (\(lang))")
}
// 10. Hello World with JSON structure
struct HelloResponse: Codable {
let message: String
let timestamp: Date
let success: Bool
}
let response = HelloResponse(
message: "Hello, World!",
timestamp: Date(),
success: true
)
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601
if let data = try? encoder.encode(response),
let jsonString = String(data: data, encoding: .utf8) {
print(jsonString)
}
// Basic data types examples
// Swift is type-safe with type inference
let integer: Int = 42
let float: Double = 3.14
let string: String = "Hello, Swift!"
let boolean: Bool = true
let array: [Int] = [1, 2, 3, 4, 5]
let dictionary: [String: Any] = [
"name": "John Doe",
"age": 30,
"email": "[email protected]"
]
let optional: String? = nil
print("Integer: \(integer), Type: \(type(of: integer))")
print("Float: \(float), Type: \(type(of: float))")
print("String: \(string), Type: \(type(of: string))")
print("Boolean: \(boolean), Type: \(type(of: boolean))")
print("Array: \(array), Type: \(type(of: array))")
print("Dictionary: \(dictionary), Type: \(type(of: dictionary))")
print("Optional: \(optional ?? "nil"), Type: \(type(of: optional))")
// Control flow examples
let age = 18
if age >= 18 {
print("You are an adult")
} else {
print("You are a minor")
}
// Switch statement
let grade = "A"
switch grade {
case "A":
print("Excellent!")
case "B":
print("Good job!")
case "C":
print("Fair enough")
default:
print("Need improvement")
}
// Loop examples
let fruits = ["apple", "banana", "cherry"]
for fruit in fruits {
print("I like \(fruit)")
}
// Range operations
for i in 1...10 {
print("Number: \(i)")
}
// Array methods examples
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let evenNumbers = numbers.filter { $0 % 2 == 0 }
let squaredNumbers = numbers.map { $0 * $0 }
let sum = numbers.reduce(0, +)
print("Even numbers: \(evenNumbers)")
print("Squared numbers: \(squaredNumbers)")
print("Sum: \(sum)")
// String methods examples
let text = "Hello, Swift Programming!"
print("Uppercase: \(text.uppercased())")
print("Lowercase: \(text.lowercased())")
print("Capitalized: \(text.capitalized)")
print("Count: \(text.count)")
print("Reversed: \(String(text.reversed()))")
// Method chaining with functional programming
let result = numbers
.filter { $0 % 2 == 0 }
.map { $0 * $0 }
.reduce(0, +)
print("Result of chained operations: \(result)")
// Tuples
func calculateStats(_ numbers: [Int]) -> (min: Int, max: Int, average: Double) {
guard !numbers.isEmpty else { return (0, 0, 0.0) }
let min = numbers.min()!
let max = numbers.max()!
let average = Double(numbers.reduce(0, +)) / Double(numbers.count)
return (min, max, average)
}
let stats = calculateStats(numbers)
print("Min: \(stats.min), Max: \(stats.max), Average: \(stats.average)")
// Enums with associated values
enum NetworkResult {
case success(data: Data)
case failure(error: Error)
case loading
}
func fetchNetworkData() -> NetworkResult {
// Simulate network operation
return .success(data: "Sample data".data(using: .utf8)!)
}
let networkResult = fetchNetworkData()
switch networkResult {
case .success(let data):
print("Success: data size \(data.count) bytes")
case .failure(let error):
print("Failure: \(error.localizedDescription)")
case .loading:
print("Loading...")
}
// Protocols
protocol Drawable {
func draw()
}
struct Circle: Drawable {
var radius: Double
func draw() {
print("Drawing a circle with radius \(radius)")
}
}
struct Square: Drawable {
var side: Double
func draw() {
print("Drawing a square with side \(side)")
}
}
let shapes: [Drawable] = [Circle(radius: 5.0), Square(side: 3.0)]
for shape in shapes {
shape.draw()
}
// Extensions
extension Int {
func isEven() -> Bool {
return self % 2 == 0
}
func squared() -> Int {
return self * self
}
}
let number = 8
print("\(number) is even: \(number.isEven())")
print("\(number) squared: \(number.squared())")
// Error handling
enum CustomError: Error {
case invalidInput
case networkError(String)
case unknownError
}
func processData(_ input: String?) throws -> String {
guard let input = input else {
throw CustomError.invalidInput
}
if input.isEmpty {
throw CustomError.invalidInput
}
return input.uppercased()
}
do {
let result = try processData("hello")
print("Processed result: \(result)")
} catch CustomError.invalidInput {
print("Invalid input provided")
} catch {
print("Unknown error: \(error)")
}
// Closures
let numbersAgain = [1, 2, 3, 4, 5]
// Using closures with filter and map
let filteredSquared = numbersAgain.filter { $0 > 2 }.map { $0 * $0 }
print("Filtered and squared: \(filteredSquared)")
// Closure as parameter
func applyOperation(_ numbers: [Int], operation: (Int) -> Int) -> [Int] {
return numbers.map(operation)
}
let doubled = applyOperation(numbersAgain) { $0 * 2 }
print("Doubled: \(doubled)")
// Property wrappers
@propertyWrapper
struct Capitalized {
private var value = ""
var wrappedValue: String {
get { value }
set { value = newValue.capitalized }
}
}
struct UserProfile {
@Capitalized var firstName: String
@Capitalized var lastName: String
}
var profile = UserProfile(firstName: "john", lastName: "doe")
print("Name: \(profile.firstName) \(profile.lastName)")
// Generics
struct Stack<Element> {
private var items: [Element] = []
mutating func push(_ item: Element) {
items.append(item)
}
mutating func pop() -> Element? {
return items.popLast()
}
var isEmpty: Bool {
return items.isEmpty
}
var count: Int {
return items.count
}
}
var stringStack = Stack<String>()
stringStack.push("Hello")
stringStack.push("World")
print("Stack count: \(stringStack.count)")
if let popped = stringStack.pop() {
print("Popped: \(popped)")
}
// Result type
func divide(_ a: Double, by b: Double) -> Result<Double, Error> {
guard b != 0 else {
return .failure(CustomError.invalidInput)
}
return .success(a / b)
}
let divisionResult = divide(10, by: 2)
switch divisionResult {
case .success(let result):
print("Division result: \(result)")
case .failure(let error):
print("Division error: \(error)")
}
// Async/await (Swift 5.5+)
func fetchUserData() async -> String {
// Simulate async network call
try? await Task.sleep(nanoseconds: 1_000_000_000)
return "User data fetched"
}
Task {
let userData = await fetchUserData()
print(userData)
}
// Main function execution
print("\nSwift Hello World examples completed!")
💻 Fondamentaux SwiftUI swift
🟡 intermediate
⭐⭐⭐
Développement d'interface SwiftUI moderne avec UI déclaratif et programmation réactive
⏱️ 25 min
🏷️ swiftui, ios, declarative ui
Prerequisites:
Swift basics, iOS development concepts, Xcode
import SwiftUI
// SwiftUI Basic Examples
// 1. Simple Text View
struct ContentView: View {
var body: some View {
Text("Hello, SwiftUI!")
.font(.largeTitle)
.fontWeight(.bold)
.foregroundColor(.blue)
.padding()
}
}
// 2. Basic Layout with Stack
struct BasicLayoutView: View {
var body: some View {
VStack(spacing: 20) {
Text("Welcome to SwiftUI")
.font(.title)
.fontWeight(.bold)
Text("Declarative UI Framework")
.font(.subheadline)
.foregroundColor(.gray)
HStack(spacing: 10) {
Button("Cancel") {
print("Cancel tapped")
}
.padding()
.background(Color.gray)
.foregroundColor(.white)
.cornerRadius(8)
Button("Confirm") {
print("Confirm tapped")
}
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(8)
}
}
.padding()
}
}
// 3. List View
struct BasicListView: View {
let fruits = ["Apple", "Banana", "Orange", "Grape", "Strawberry"]
var body: some View {
NavigationView {
List(fruits, id: \.self) { fruit in
Text(fruit)
.font(.headline)
.padding(.vertical, 4)
}
.navigationTitle("Fruits")
}
}
}
// 4. State Management with @State
struct CounterView: View {
@State private var count = 0
var body: some View {
VStack(spacing: 20) {
Text("Counter: \(count)")
.font(.largeTitle)
.fontWeight(.bold)
HStack(spacing: 20) {
Button("-") {
count -= 1
}
.font(.title)
.frame(width: 50, height: 50)
.background(Color.red)
.foregroundColor(.white)
.cornerRadius(25)
Button("+") {
count += 1
}
.font(.title)
.frame(width: 50, height: 50)
.background(Color.green)
.foregroundColor(.white)
.cornerRadius(25)
}
Button("Reset") {
count = 0
}
.padding()
.background(Color.orange)
.foregroundColor(.white)
.cornerRadius(8)
}
.padding()
}
}
// 5. Custom View with Properties
struct UserCardView: View {
let name: String
let email: String
let avatar: String
@State private var isLiked = false
var body: some View {
HStack(spacing: 15) {
Image(systemName: avatar)
.font(.largeTitle)
.foregroundColor(.blue)
.frame(width: 60, height: 60)
.background(Color.gray.opacity(0.1))
.cornerRadius(30)
VStack(alignment: .leading, spacing: 5) {
Text(name)
.font(.headline)
.fontWeight(.semibold)
Text(email)
.font(.caption)
.foregroundColor(.gray)
}
Spacer()
Button(action: {
isLiked.toggle()
}) {
Image(systemName: isLiked ? "heart.fill" : "heart")
.font(.title2)
.foregroundColor(isLiked ? .red : .gray)
}
}
.padding()
.background(Color.white)
.cornerRadius(12)
.shadow(color: .gray.opacity(0.3), radius: 5, x: 0, y: 2)
}
}
// 6. Form with Input Fields
struct RegistrationForm: View {
@State private var username = ""
@State private var email = ""
@State private var password = ""
@State private var confirmPassword = ""
@State private var agreeToTerms = false
@State private var showingAlert = false
private var isFormValid: Bool {
!username.isEmpty &&
!email.isEmpty &&
email.contains("@") &&
password.count >= 8 &&
password == confirmPassword &&
agreeToTerms
}
var body: some View {
NavigationView {
Form {
Section(header: Text("Account Information")) {
TextField("Username", text: $username)
.autocapitalization(.none)
.disableAutocorrection(true)
TextField("Email", text: $email)
.keyboardType(.emailAddress)
.autocapitalization(.none)
.disableAutocorrection(true)
SecureField("Password", text: $password)
SecureField("Confirm Password", text: $confirmPassword)
}
Section(header: Text("Terms")) {
Toggle("I agree to the terms and conditions", isOn: $agreeToTerms)
}
Section {
Button(action: {
if isFormValid {
showingAlert = true
}
}) {
Text("Create Account")
.frame(maxWidth: .infinity)
.foregroundColor(.white)
}
.disabled(!isFormValid)
.listRowBackground(isFormValid ? Color.blue : Color.gray)
}
}
.navigationTitle("Sign Up")
.alert("Success", isPresented: $showingAlert) {
Button("OK") { }
} message: {
Text("Account created successfully!")
}
}
}
}
// 7. Tab View Structure
struct TabContainer: View {
var body: some View {
TabView {
HomeView()
.tabItem {
Image(systemName: "house.fill")
Text("Home")
}
SearchView()
.tabItem {
Image(systemName: "magnifyingglass")
Text("Search")
}
ProfileView()
.tabItem {
Image(systemName: "person.fill")
Text("Profile")
}
}
}
}
struct HomeView: View {
var body: some View {
NavigationView {
VStack {
Text("Home Screen")
.font(.largeTitle)
Spacer()
}
.navigationTitle("Home")
}
}
}
struct SearchView: View {
var body: some View {
NavigationView {
VStack {
Text("Search Screen")
.font(.largeTitle)
Spacer()
}
.navigationTitle("Search")
}
}
}
struct ProfileView: View {
var body: some View {
NavigationView {
VStack {
Text("Profile Screen")
.font(.largeTitle)
Spacer()
}
.navigationTitle("Profile")
}
}
}
// 8. Modal Presentation
struct ModalExample: View {
@State private var showingModal = false
var body: some View {
VStack(spacing: 20) {
Text("Modal Example")
.font(.title)
Button("Show Modal") {
showingModal = true
}
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(10)
}
.sheet(isPresented: $showingModal) {
ModalView(showingModal: $showingModal)
}
}
}
struct ModalView: View {
@Binding var showingModal: Bool
@State private var modalText = ""
var body: some View {
NavigationView {
VStack(spacing: 20) {
TextField("Enter text", text: $modalText)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding()
if !modalText.isEmpty {
Text("You entered: \(modalText)")
.font(.headline)
.foregroundColor(.blue)
}
Spacer()
Button("Close") {
showingModal = false
}
.padding()
.background(Color.red)
.foregroundColor(.white)
.cornerRadius(10)
}
.padding()
.navigationTitle("Modal")
.navigationBarItems(trailing: Button("Done") { showingModal = false })
}
}
}
// 9. Animation Example
struct AnimationExample: View {
@State private var isAnimating = false
@State private var rotation: Double = 0
var body: some View {
VStack(spacing: 30) {
// Scale animation
Circle()
.fill(Color.blue)
.frame(width: 100, height: 100)
.scaleEffect(isAnimating ? 1.5 : 1.0)
.animation(.easeInOut(duration: 1.0), value: isAnimating)
// Rotation animation
Rectangle()
.fill(Color.green)
.frame(width: 100, height: 100)
.rotationEffect(.degrees(rotation))
.animation(.linear(duration: 2.0).repeatForever(autoreverses: false), value: rotation)
// Position animation
Circle()
.fill(Color.orange)
.frame(width: 50, height: 50)
.offset(x: isAnimating ? 100 : -100)
.animation(.spring(response: 1.0, dampingFraction: 0.5), value: isAnimating)
Button("Animate") {
withAnimation {
isAnimating.toggle()
}
rotation += 360
}
.padding()
.background(Color.purple)
.foregroundColor(.white)
.cornerRadius(10)
}
.onAppear {
rotation = 360
}
}
}
// 10. Custom Modifier
struct CustomCard<Content: View>: View {
let content: Content
init(@ViewBuilder content: () -> Content) {
self.content = content()
}
var body: some View {
content
.padding()
.background(Color.white)
.cornerRadius(12)
.shadow(color: .black.opacity(0.1), radius: 5, x: 0, y: 2)
}
}
// Custom View Extension
extension View {
func customCard() -> some View {
CustomCard {
self
}
}
}
struct CustomModifierExample: View {
var body: some View {
VStack(spacing: 20) {
Text("Custom Card Modifier")
.font(.title)
.customCard()
Text("Another custom card")
.customCard()
Text("Yet another one")
.customCard()
}
.padding()
}
}
// 11. Environment Object Example
class UserSettings: ObservableObject {
@Published var username = "Guest"
@Published var isDarkMode = false
@Published var notificationsEnabled = true
}
struct SettingsView: View {
@EnvironmentObject var settings: UserSettings
var body: some View {
Form {
Section(header: Text("Profile")) {
TextField("Username", text: $settings.username)
}
Section(header: Text("Appearance")) {
Toggle("Dark Mode", isOn: $settings.isDarkMode)
}
Section(header: Text("Notifications")) {
Toggle("Enable Notifications", isOn: $settings.notificationsEnabled)
}
}
.navigationTitle("Settings")
}
}
struct MainApp: View {
@StateObject private var settings = UserSettings()
var body: some View {
TabContainer()
.environmentObject(settings)
}
}
// Preview providers
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
Group {
ContentView()
BasicLayoutView()
CounterView()
UserCardView(name: "John Doe", email: "[email protected]", avatar: "person.circle")
RegistrationForm()
}
}
}
💻 Concurrence et Async Swift swift
🔴 complex
⭐⭐⭐⭐⭐
Concurrence moderne Swift avec async/await, actors et concurrence structurée
⏱️ 40 min
🏷️ swift, concurrency, async, actors, ios
Prerequisites:
Advanced Swift, GCD basics, Modern Swift (5.5+)
// Swift Concurrency Examples (Swift 5.5+)
import Foundation
// 1. Basic async/await
func fetchUserData() async throws -> User {
// Simulate network delay
try await Task.sleep(nanoseconds: 2_000_000_000)
return User(
id: UUID(),
name: "John Doe",
email: "[email protected]",
avatar: "person.circle"
)
}
struct User: Codable, Identifiable {
let id: UUID
let name: String
let email: String
let avatar: String
}
// Usage
func loadUser() async {
do {
let user = try await fetchUserData()
print("Loaded user: \(user.name)")
} catch {
print("Error loading user: \(error)")
}
}
// 2. AsyncSequence
struct NumberGenerator: AsyncSequence {
typealias Element = Int
func makeAsyncIterator() -> AsyncIterator {
AsyncIterator()
}
struct AsyncIterator: AsyncIteratorProtocol {
private var current = 1
mutating func next() async -> Int? {
if current <= 10 {
defer { current += 1 }
return current
}
return nil
}
}
}
func processNumbers() async {
let numbers = NumberGenerator()
for await number in numbers {
print("Processing number: \(number)")
// Simulate async work
try? await Task.sleep(nanoseconds: 500_000_000)
}
}
// 3. Task Groups
func fetchMultipleUsers(ids: [UUID]) async throws -> [User] {
try await withThrowingTaskGroup(of: User.self) { group in
var results: [User] = []
for id in ids {
group.addTask {
return try await fetchUserById(id)
}
}
for try await user in group {
results.append(user)
}
return results
}
}
func fetchUserById(_ id: UUID) async throws -> User {
// Simulate different user data
try await Task.sleep(nanoseconds: 1_000_000_000)
return User(
id: id,
name: "User \(id.uuidString.prefix(8))",
email: "user\(id.uuidString.prefix(8))@example.com",
avatar: "person.circle"
)
}
// Usage
func loadMultipleUsers() async {
do {
let ids = [UUID(), UUID(), UUID()]
let users = try await fetchMultipleUsers(ids: ids)
print("Loaded \(users.count) users")
for user in users {
print("- \(user.name)")
}
} catch {
print("Error: \(error)")
}
}
// 4. Actor for Thread Safety
actor Counter {
private var value = 0
func increment() {
value += 1
}
func decrement() {
value -= 1
}
func getValue() -> Int {
return value
}
func reset() {
value = 0
}
}
// Usage
func testActor() async {
let counter = Counter()
await counter.increment()
await counter.increment()
await counter.increment()
let currentValue = await counter.getValue()
print("Counter value: \(currentValue)")
await counter.reset()
print("Counter reset")
}
// 5. AsyncImage (SwiftUI)
import SwiftUI
struct AsyncImageView: View {
private let imageUrl = URL(string: "https://picsum.photos/200/300")
var body: some View {
AsyncImage(url: imageUrl) { phase in
switch phase {
case .empty:
ProgressView()
.frame(width: 200, height: 300)
case .success(let image):
image
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 200, height: 300)
.cornerRadius(10)
case .failure(_):
Image(systemName: "photo")
.foregroundColor(.gray)
.frame(width: 200, height: 300)
@unknown default:
EmptyView()
}
}
}
}
// 6. Continuations
func fetchWithContinuation() async -> String {
return await withCheckedContinuation { continuation in
// Simulate callback-based API
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
continuation.resume(returning: "Data loaded with continuation")
}
}
}
// 7. Async/Await with Combine
import Combine
class AsyncViewModel: ObservableObject {
@Published var users: [User] = []
@Published var isLoading = false
@Published var errorMessage: String?
private var cancellables = Set<AnyCancellable>()
func loadUsers() async {
isLoading = true
errorMessage = nil
do {
let ids = [UUID(), UUID(), UUID()]
let fetchedUsers = try await fetchMultipleUsers(ids: ids)
await MainActor.run {
self.users = fetchedUsers
self.isLoading = false
}
} catch {
await MainActor.run {
self.errorMessage = error.localizedDescription
self.isLoading = false
}
}
}
func refreshUsers() async {
await loadUsers()
}
}
// 8. Structured Concurrency with Cancellation
func fetchWithCancellation() async {
let task = Task {
try await fetchUserData()
}
// Simulate cancellation after 1 second
Task {
try? await Task.sleep(nanoseconds: 1_000_000_000)
task.cancel()
}
do {
let user = try await task.value
print("User fetched: \(user.name)")
} catch is CancellationError {
print("Task was cancelled")
} catch {
print("Error: \(error)")
}
}
// 9. Async Stream
struct EventStream: AsyncStream {
typealias Element = String
init() {
self = AsyncStream { continuation in
Task {
for i in 1...10 {
continuation.yield("Event \(i)")
try? await Task.sleep(nanoseconds: 500_000_000)
}
continuation.finish()
}
}
}
}
func processEvents() async {
let events = EventStream()
for await event in events {
print("Received: \(event)")
}
print("Stream finished")
}
// 10. Task Priorities
func testTaskPriorities() async {
let highPriorityTask = Task(priority: .high) {
print("High priority task started")
try? await Task.sleep(nanoseconds: 2_000_000_000)
print("High priority task completed")
}
let lowPriorityTask = Task(priority: .low) {
print("Low priority task started")
try? await Task.sleep(nanoseconds: 1_000_000_000)
print("Low priority task completed")
}
await highPriorityTask.value
await lowPriorityTask.value
}
// 11. Detached Tasks
func testDetachedTask() {
Task.detached {
print("Detached task running")
try? await Task.sleep(nanoseconds: 1_000_000_000)
print("Detached task completed")
}
}
// 12. Actor Isolation with Main Actor
@MainActor
class MainActorViewModel: ObservableObject {
@Published var counter = 0
@Published var message = ""
func increment() {
counter += 1
message = "Counter: \(counter)"
}
func performBackgroundWork() async {
let result = await backgroundCalculation()
message = "Result: \(result)"
}
private func backgroundCalculation() async -> Int {
// This runs in background
try? await Task.sleep(nanoseconds: 2_000_000_000)
return 42
}
}
// 13. Async Property Wrapper
@propertyWrapper
struct AsyncProperty<Value> {
private var _value: Value?
private var task: Task<Value, Error>?
var wrappedValue: Value {
get async throws {
if let value = _value {
return value
}
guard let task = task else {
throw AsyncPropertyError.notInitialized
}
let value = try await task.value
_value = value
return value
}
}
init(wrappedValue: () async throws -> Value) {
task = Task {
try await wrappedValue()
}
}
}
enum AsyncPropertyError: Error {
case notInitialized
}
struct AsyncPropertyExample {
@AsyncProperty private var data: String
init() {
_data = AsyncProperty {
try await Task.sleep(nanoseconds: 2_000_000_000)
return "Async data loaded"
}
}
func loadData() async throws -> String {
return try await _data
}
}
// 14. Concurrency with File Operations
actor FileManagerActor {
private var cache: [URL: Data] = [:]
func readFile(_ url: URL) async throws -> Data {
if let cachedData = cache[url] {
return cachedData
}
let data = try Data(contentsOf: url)
cache[url] = data
return data
}
func clearCache() {
cache.removeAll()
}
}
// Main execution function
func runConcurrencyExamples() async {
print("=== Swift Concurrency Examples ===\n")
// Basic async/await
print("1. Basic async/await:")
await loadUser()
// AsyncSequence
print("\n2. AsyncSequence:")
await processNumbers()
// Actor
print("\n3. Actor example:")
await testActor()
// Task Groups
print("\n4. Task Groups:")
await loadMultipleUsers()
// Continuations
print("\n5. Continuations:")
let result = await fetchWithContinuation()
print(result)
// Async Stream
print("\n6. Async Stream:")
await processEvents()
// Task Priorities
print("\n7. Task Priorities:")
await testTaskPriorities()
// Async Property
print("\n8. Async Property:")
do {
let example = AsyncPropertyExample()
let data = try await example.loadData()
print(data)
} catch {
print("Error: \(error)")
}
print("\n=== Concurrency Examples Completed ===")
}
// Execute the examples
Task {
await runConcurrencyExamples()
}