You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift 6下Environment值非Sendable类型编译错误及解决

Swift 6下SwiftUI环境变量的并发问题与解决

问题1:环境变量类型不满足Sendable要求

在SwiftUI中使用Environment(.showMessage)实现消息显示/隐藏时,Swift 6编译报错:

Static property 'defaultValue' is not concurrency-safe because non-'Sendable' type 'ShowMessageAction' may have shared mutable state.

相关代码:

struct ShowMessageAction {
    typealias Action = (String, MessageType) -> ()
    let action: Action
    func callAsFunction(_ message: String, _ messageType: MessageType = .error) {
        action(message, messageType)
    }
}

extension EnvironmentValues {
    @Entry var showMessage = ShowMessageAction { _, _ in }
}

问题2:视图初始化的主Actor隔离问题

修复上述问题后,MyProductListScreen出现新错误:

Call to main actor-isolated initializer 'init()' in a synchronous nonisolated context

调用代码:

NavigationStack {
    MyProductListScreen()
}

MyProductListScreen定义:

struct MyProductListScreen: View {
    // 报错指向showMessage
    @Environment(\.showMessage) private var showMessage
    @Environment(ProductStore.self) private var productStore
    @State private var isPresented: Bool = false
    @AppStorage("userId") private var userId: Int?
}

最终解决方案

将构建视图的destination属性标记为@MainActor即可解决:

@MainActor
@ViewBuilder
var destination: some View {
    switch self {
        case .home:
        NavigationStack {
            ProductListScreen()
        }
        case .myProducts:
        NavigationStack {
            MyProductListScreen()
                    .requiresAuthentication()
        }
    }
}

内容的提问来源于stack exchange,提问作者john doe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 23:29:54