Elysia Tools

Explore ferramentas, exemplos, explicações visuais e guias temáticos em um espaço claro.

Categorias populares

Temas

Idioma
ZHESPTRUFRDEEN

Elysia Tools

Navegação

Linguagens de programação

Exemplos Swift

Exemplos de código Swift essenciais para desenvolvimento iOS, incluindo recursos modernos do Swift e SwiftUI

Exemplos

Entradas desta coleção

CódigoswiftSimples

Hello World Swift

Programa Hello World básico com sintaxe moderna Swift e conceitos de desenvolvimento iOS

Dificuldade

3/10

Tempo estimado

15 min

Etiquetas

swift, ios, functional programming

Pré-requisitos

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": "[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!")
CódigoswiftIntermediário

Fundamentos SwiftUI

Desenvolvimento de interface SwiftUI moderno com UI declarativo e programação reativa

Dificuldade

6/10

Tempo estimado

25 min

Etiquetas

swiftui, ios, declarative ui

Pré-requisitos

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: "[email protected]", avatar: "person.circle")
            RegistrationForm()
        }
    }
}
CódigoswiftComplexo

Concorrência e Async Swift

Concorrência moderna Swift com async/await, actors e concorrência estruturada

Dificuldade

9/10

Tempo estimado

40 min

Etiquetas

swift, concurrency, async, actors, ios

Pré-requisitos

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: "[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()
}

Ferramentas

Ferramentas frequentemente usadas com este exemplo

Relacionado

Coleções de exemplos relacionadas

Relacionado

Temas relacionados

Tema

Verificação de formato de identificadores financeiros e fiscais

Confira cartões, IBAN/SWIFT, VAT da UE e EIN dos EUA por sintaxe, comprimento, regras nacionais e dígitos verificadores aplicáveis, sem confundir formato válido com conta ou registro ativo.

Tema

Revisão e entrega de um componente de sorteio auto-hospedado

Revise configuração, exemplos de respostas, legibilidade e visualização responsiva antes de entregar os arquivos e as evidências de integração do sorteio.

Tema

Modelos farmacocineticos didaticos e checagem de resultados

Explore formulas farmacocineticas, hipoteses de modelo e consistencia de resultados para ensino ou QA, sem doseamento ou conselho clinico.

Tema

Ferramentas de cifras clássicas e modernas

Pratique cifras com segurança em contextos educacionais ou CTF, comparando transformações clássicas reversíveis com criptografia moderna e seus limites.

Início
Ferramentas3208
Exemplos593
Visualizações469
Visualizadores de arquivos103
Temas237
Etiquetas333
Imagens, áudio e vídeo657

Ferramentas de processamento, conversão e otimização de imagens, áudio e vídeo

Matemática, datas e finanças646

Calculadoras, ferramentas numéricas, lógica de datas, estatística e finanças

Design e cor298

Ferramentas de cor, layout, gráficos, estilo visual e apoio ao design

Texto e escrita209

Ferramentas de escrita, limpeza, formatação, extração e análise de texto

Desenvolvimento e Web193

Utilitários para desenvolvedores, rede, depuração web e automação

Conversão e codificação175

Ferramentas de conversão de formatos, arquivos, unidades, arquivos compactados e codificação

Hábitos privados: backup, restauração e revisão para partilha
De artigo a rascunhos de X e LinkedIn: revisão factual e entrega
Revisão de aula Markdown interativa e entrega offline
Revisão de móveis em um quarto pequeno e entrega para mudança
Triagem de fontes FLAC/WAV e entrega de evidências

© 2026 Elysia Tools. Todos os direitos reservados.

DocumentaçãoPreçosSobreTermos de serviçoPolítica de privacidadeCookiesContato

Media

Conversor de AVI para MP4

Converte arquivos de vídeo AVI para formato MP4

Media

Conversor de MP4 para AVI

Converte arquivos de vídeo MP4 para formato AVI

Media

Conversor de Video em Lote

Converta múltiplos arquivos de video entre diferentes formatos como MP4, WebM, MKV, AVI, MOV com configurações de qualidade e processamento em lote

Media

Cortador de Vídeo

Cortar e aparar clipes de vídeo com precisão, suportando múltiplos formatos e configurações de qualidade

Media

Vídeo para APNG

Converter clipes de vídeo para formato APNG (PNG Animado) com suporte a transparência e melhor qualidade que GIF

Media

Vídeo para GIF Otimizado

Converte vídeos em formato GIF otimizado com configurações avançadas de compressão

Media

Vídeo para Sequência de Imagens

Extrair quadros do vídeo como sequência de imagens com taxa de quadros, qualidade e formato personalizáveis

Media

Cortar Vídeo

Cortar clipes de vídeo rapidamente - extrair segmentos com processamento rápido sem perdas

Desenvolvimento mobile

Exemplos de Flutter

Exemplos do framework de desenvolvimento móvel Dart Flutter incluindo widgets, gerenciamento de estado, navegação e integração de plataforma

Desenvolvimento mobile

Exemplos de React Native

Exemplos de desenvolvimento mobile multiplataforma React Native incluindo componentes, navegação, gerenciamento de estado e integração nativa

Mídia

Exemplos de Códigos QR

Imagens de código QR de exemplo para testar ferramentas de leitura e geração de código QR

Linguagens de programação

Exemplos da Linguagem Lua

Exemplos essenciais de programação Lua para desenvolvimento de jogos e scripts embutidos

Testes

BDD with Cucumber - Práticas de Desenvolvimento Orientado a Comportamento

Exemplos abrangentes de Cucumber BDD incluindo arquivos de feature, definições de passo, tabelas de dados, hooks e padrões BDD avançados para desenvolvimento colaborativo

Mensageria

Exemplos Apache Pulsar

Exemplos Apache Pulsar incluindo pub/sub, readers, consumers com diferentes tipos de subscrição, gerenciamento de schema e armazenamento tiered para mensageria empresarial