Skip to content

Instantly share code, notes, and snippets.

@simsaens
Created July 20, 2024 13:42
Show Gist options
  • Save simsaens/d815226e5f766fae5d23355c019c013d to your computer and use it in GitHub Desktop.
Save simsaens/d815226e5f766fae5d23355c019c013d to your computer and use it in GitHub Desktop.
Unsure why warnings show in the second example unless the method is marked @mainactor
import AVFoundation
class Foo {
var x: AVAudioFile?
func someOtherMethod() async throws {
x = try AVAudioFile(forReading: URL(fileURLWithPath: "/path/to/file.m4a"))
}
//@MainActor annotation is not needed here and there are no warnings, why is it needed below?
func bar(completionHandler: @escaping (Error?)->Void) {
Task {
do {
try await self.someOtherMethod()
completionHandler(nil)
} catch {
completionHandler(error)
}
}
}
}
extension AVAssetExportSession {
//@MainActor //uncomment this to silence warnings
func export(to url: URL, as fileType: AVFileType, completionHandler: @escaping (Error?)->Void) {
if #available(iOS 18, macOS 15, tvOS 15, visionOS 2, *) {
Task {
do {
try await export(to: url, as: fileType, isolation: #isolation)
completionHandler(nil)
} catch {
completionHandler(error)
}
}
} else {
outputURL = url
outputFileType = fileType
Task {
await withCheckedContinuation { continuation in
exportAsynchronously {
continuation.resume()
}
}
completionHandler(error)
}
}
}
}
@mattmassicotte
Copy link

Right away, I am definitely seeing warnings here. And that makes sense, the stuff going in to Task has to be Sendable. Making this MainActor prevents the isolation domains from needing to be crossed.

        // @MainActor annotation is not needed here and there are no warnings, why is it needed below?
	func bar(completionHandler: @escaping (Error?) -> Void) {
		Task {
			do {
// WARNING: Capture of 'self' with non-sendable type 'Foo' in a `@Sendable` closure; this is an error in the Swift 6 language mode
				try await self.someOtherMethod()
// WANRING: Capture of 'completionHandler' with non-sendable type '((any Error)?) -> Void' in a `@Sendable` closure; this is an error in the Swift 6 language mode
				completionHandler(nil)
			} catch {
				completionHandler(error)
			}
		}
	}

@simsaens
Copy link
Author

That is odd @mattmassicotte — I don't get those warning in Xcode 16 Beta
image

This had made me assume the Task inherits the isolation domain from the caller of the function it is defined in (not sure if that even makes sense?)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment