UnsafeMutablePointer
不再是 Sendable
,并且在 Xcode 16 Beta 中使用构建设置“严格并发检查”,从另一个
pointee
设置
pointer
的
actor
(正确吗?)会发出警告。设置:
问题:
下面的代码给出警告
Capture of 'shouldStopPointer' with non-sendable type 'UnsafeMutablePointer<ObjCBool>' in a @Sendable closure; this is an error in the Swift 6 language mode. Generic struct 'UnsafeMutablePointer' does not conform to the 'Sendable' protocol (Swift.UnsafeMutablePointer)
如何将指针设置在正确的演员中,或者以其他方式防止此警告?
截图:代码:
import SwiftUI import Photos
actor DifferentActor {
func requestMetaData(progressHandler: @escaping PHAssetImageProgressHandler) async -> CGImagePropertyOrientation {
let options = PHImageRequestOptions()
options.isNetworkAccessAllowed = true
options.deliveryMode = .opportunistic
options.progressHandler = progressHandler
let someAsset = PHAsset()
let orientation = await withCheckedContinuation { continuation in
PHImageManager.default().requestImageDataAndOrientation(for: someAsset, options: options) { imageData, dataUTI, orientation, status in
continuation.resume(returning: orientation)
}
}
return orientation
} }
@MainActor struct ContentView: View {
let differentActor = DifferentActor()
@State var photoMetadata: String?
@State var progress: Double = 0.0
@State var shouldStopGettingMetadata: Bool = false
var body: some View {
VStack(spacing: 20) {
Button("Get metadata") {
Task {
await downloadMetaData()
}
}
HStack {
Text("Progress: ")
ProgressView(value: progress)
}
Button("Cancel get metadata") {
shouldStopGettingMetadata = true
}
Text("Orientation: \(photoMetadata ?? "Not yet loaded")")
}
}
private func downloadMetaData() async {
let orientation = await differentActor.requestMetaData { @Sendable progress, error, shouldStopPointer, info in
Task { @MainActor in
self.progress = progress
if self.shouldStopGettingMetadata {
shouldStopPointer.pointee = true
}
}
}
self.photoMetadata = "\(orientation)"
}
}
#Preview {
ContentView() }
如果我将所有内容设为异步,则会收到不同的错误:
Cannot pass function of type '@Sendable (Double, (any Error)?, UnsafeMutablePointer<ObjCBool>, [AnyHashable : Any]?) async -> Void' to parameter expecting synchronous function type
截图:代码:
private func downloadMetaData() async {
let orientation = await differentActor.requestMetaData { @Sendable progress, error, shouldStopPointer, info in
await self.progress = progress
let shouldStop = self.shouldStopGettingMetadata
if shouldStop {
shouldStopPointer.pointee = true
}
}
self.photoMetadata = "\(orientation)"
}
@unchecked Sendable
extension UnsafeMutablePointer<ObjCBool>: @unchecked Sendable {}
或在 Xcode 16 中:
extension UnsafeMutablePointer<ObjCBool>: @unchecked @retroactive Sendable {}
请参阅 https://forums.swift.org/t/unsafepointer-sendable-should-be-revoked/51926 和 https://github.com/swiftlang/swift/pull/39218