swiftswiftuiasync-await

task (lowercased) vs. Task (capitalized)


What's the difference?

task {
    // ... //
}
                
Task {
    // ... //
}

I discovered it by accident.

Task is the right struct, when you want to create an asynchronous task. But writing task doesn't cause a syntax error. I know the SwiftUI task-modifier. But what is the purpose written within general code?


Solution

  • You can write a modifier without the dot as part of other code but I am not sure it will work very well.

    So the task you have is the same as the modifier version and is required to return a View meaning you should really be using Task if you are inside a function. Note that

    Here is a silly example with a function that is declared inside a view that we can learn two things from, 1) the task closure is never executed, only "Hello" is printed 2) We can add other modifiers here and they won't be useful either.

    func silly() {
        Task {
            try await Task.sleep(for: .seconds(1))
            print("Hello")
        }
    
    
        task {
            try? await Task.sleep(for: .seconds(1))
    
            print("Hello 2")
        }
    
        font(.largeTitle)
    
    }