Elysia Tools

在一个清晰的工作台里浏览工具、案例、可视化和主题指南。

热门分类

专题

语言
ZHDERUPTENFRES

Elysia Tools

导航

编程语言

Swift 示例

基础Swift代码示例,包括iOS开发、现代Swift特性和SwiftUI

案例

这个案例集合中的条目

代码swift简单

Swift Hello World

基础Swift Hello World程序和现代Swift语法及iOS开发概念

难度

3/10

预计时间

15 min

标签

swift, ios, functional programming

前置条件

Basic programming concepts

swift
// 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 greetingList = ["Hello", "Bonjour", "Hola", "Ciao", "こんにちは"]
for greeting in greetingList {
    print("\(greeting), World!")
}

// 9. Hello World with dictionary
let greetingMap: [String: String] = [
    "en": "Hello",
    "es": "Hola",
    "fr": "Bonjour",
    "de": "Hallo",
    "ja": "こんにちは"
]

for (lang, greeting) in greetingMap {
    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": "john@example.com"
]
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!")
代码swift中等

SwiftUI 基础

现代SwiftUI界面开发,包括声明式UI和响应式编程

难度

6/10

预计时间

25 min

标签

swiftui, ios, declarative ui

前置条件

Swift basics, iOS development concepts, Xcode

swift
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: "john@example.com", avatar: "person.circle")
            RegistrationForm()
        }
    }
}
代码swift复杂

Swift 并发与异步

现代Swift并发编程,包括async/await、actors和结构化并发

难度

9/10

预计时间

40 min

标签

swift, concurrency, async, actors, ios

前置条件

Advanced Swift, GCD basics, Modern Swift (5.5+)

swift
// 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: "john@example.com",
        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()
}

工具

经常与该案例搭配使用的工具

相关内容

相关案例集合

相关内容

相关专题

专题

金融与税务标识符格式检查

检查信用卡号、IBAN/SWIFT、欧盟 VAT 号和美国 EIN 的语法、长度、国家规则及适用校验位;格式通过不等于账户、注册状态或余额可用。

专题

药代动力学教学模型与结果核查

用于教学或 QA 的药代公式、模型假设和结果一致性核查,不提供用药剂量、诊断或临床建议。

专题

经典与现代密码工具

在安全的教学或 CTF 场景中比较可逆的经典变换与现代加密,并明确玩具密码不等于安全防护。

专题

文本前后缀与包裹符号批处理,整行整词一次到位

给文本行或词批量添加前后缀,为 SQL、配置和 Markdown 给每个值加引号或反引号包裹,并剥掉粘贴列表带来的编号、符号和装饰。

首页
工具3212
案例593
可视化471
文件查看器103
专题239
标签333
图像、音频与视频657

图像、音频、视频处理、转换与优化工具

数学、日期与金融647

计算器、数值计算、日期逻辑、统计与金融工具

设计与颜色298

颜色、版式、图形、视觉样式与设计辅助工具

文本与写作209

写作、清洗、格式化、提取与文本分析工具

开发与 Web193

开发者工具、网络处理、Web 调试与自动化辅助工具

转换与编码175

格式、文件、压缩包、单位与编码转换工具

潜客测验发布与联系人交接
讣告、悼词与纪念卡的家属复核及交付
本地习惯记录的备份、恢复演练与分享前检查
长文改编 X 串文与 LinkedIn 帖子的事实复核与交付
Markdown 互动课件审校、离线演示与交付

© 2026 Elysia Tools. 保留所有权利。

文档价格关于我们服务条款隐私政策Cookie 政策联系我们

Media

AVI转MP4转换器

将AVI视频文件转换为MP4格式

Media

MP4转AVI转换器

将MP4视频文件转换为AVI格式

Media

批量视频转换器

批量转换多个视频文件格式,支持 MP4、WebM、MKV、AVI、MOV、FLV,支持质量设置和批量处理

Media

视频剪辑器

精确剪辑视频片段,支持多种格式和质量设置

Media

视频转APNG

将视频片段转换为APNG(动画PNG)格式,支持透明度且质量优于GIF

Media

视频转GIF优化版

将视频转换为优化后的GIF格式,支持高级压缩设置

Media

视频转图片序列

将视频帧提取为图片序列,支持自定义帧率、质量和输出格式

Media

视频修剪

快速修剪视频片段 - 使用快速无损处理从视频中提取片段

移动开发

Flutter 示例

Flutter Dart 移动开发框架示例,包括小部件、状态管理、导航和平台集成

移动开发

React Native 示例

React Native 跨平台移动开发示例,包括组件、导航、状态管理和原生集成

媒体

二维码示例

用于测试二维码读取和生成工具的示例二维码图像

编程语言

Lua 语言示例

Lua编程示例,用于游戏开发和嵌入式脚本

测试

BDD with Cucumber - 行为驱动开发实践

全面的 Cucumber BDD 示例,包括功能文件、步骤定义、数据表格、钩子和高级 BDD 模式,用于协作开发

消息

Apache Pulsar 示例

Apache Pulsar 示例,包括发布订阅、读取器、不同订阅类型的消费者、模式管理和分层存储,适用于企业级消息传递