swiftappkitattributedstring

Using NSFont with AttributeContainer


When creating an AttributedString for use in AppKit I get a warning that NSFont isn't Sendable:

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

The warning is correct that NSFont isn't Sendable, so is there a way to accomplish this without turning off concurrency warnings? AppKit is well behind SwiftUI and UIKit when it comes to being audited for Sendable conformance, but there's no much I can do about it. Marking the import of Foundation as @preconcurrency has no effect. A quick test project shows that the font is set properly and can be used in, say, an NSTextView. I just don't want to have to stare at those warnings until Apple gets around to AppKit refinement (historically, could be quite a while).

EDIT: I'm using Xcode 15b5. Xcode 14.3.1 doesn't show the warning.


Solution

  • You can initialize the container with a [NSAttributedString.Key : Any] dictionary. This doesn't show the warning

    let container = AttributeContainer([.foregroundColor: Color.red, 
                                        .font: NSFont.systemFont(ofSize: mySize)])