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

AppKit中使用NSFont与AttributeContainer时,如何消除Sendable警告?

问题:AppKit中NSFont未遵循Sendable协议的警告处理

在为AppKit创建AttributedString时,触发NSFont未遵循Sendable协议的警告,代码示例如下:

var container = AttributeContainer()
container.appKit.foregroundColor = .red
container.appKit.font = .systemFont(ofSize: mySize)
//  ^ Conformance of 'NSFont' to 'Sendable' is unavailable

已知NSFont确实未实现Sendable协议一致性,使用Xcode 15b5时会出现该警告(Xcode 14.3.1无此警告),需在不关闭全局并发警告的前提下解决,且@preconcurrency标记Foundation导入无效。

解决方案

1. 全局扩展NSFont添加@unchecked Sendable一致性

由于NSFont在AppKit中实际是线程安全的,仅缺少官方的Sendable协议声明,可全局添加扩展:

extension NSFont: @unchecked Sendable {}

将这段代码放在项目全局文件(如AppKitSendableFixes.swift)中,可消除所有NSFont相关的Sendable警告。@unchecked在此场景下是安全的,因为NSFont实例不包含线程不安全的可变状态。

2. 局部禁用特定警告

若不想全局修改,可在出现警告的代码处临时禁用:

var container = AttributeContainer()
container.appKit.foregroundColor = .red
// 临时禁用Sendable一致性警告
// swiftlint:disable:next sendable
container.appKit.font = .systemFont(ofSize: mySize)

未使用SwiftLint的情况下,可改用编译器指令:

var container = AttributeContainer()
container.appKit.foregroundColor = .red
// clang diagnostic push
// clang diagnostic ignored "-Wsendable-conformance"
container.appKit.font = .systemFont(ofSize: mySize)
// clang diagnostic pop

3. 调整AttributeContainer的属性设置方式

通过AttributeContainer的下标直接设置属性,配合全局扩展使用可消除警告:

var container = AttributeContainer()
container[.foregroundColor] = NSColor.red
container[.font] = NSFont.systemFont(ofSize: mySize)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 16:12:50