smr
smr

Reputation: 1203

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.

Upvotes: 3

Views: 1036

Answers (3)

vadian
vadian

Reputation: 285079

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)])

Upvotes: 8

mkeiser
mkeiser

Reputation: 973

The following got rid of the warning for me in Xcode 15.0 beta 6:

    var container = AttributeContainer()
    container.appKit.foregroundColor = .red
    // Produces a value of type `AttributeScopes.SwiftUIAttributes.FontAttribute.Value`
    container.appKit.font = .init(.systemFont(ofSize: mySize))

Upvotes: -1

smr
smr

Reputation: 1203

There doesn't seem to be a great way to deal with this. I filed a feedback (FB12885931) on the issue but...you know.

There is reason to be fairly confident in marking NSFont as Sendable as it's documented in the Cocoa Text Architecture Guide as follows: "Font objects are immutable, so it is safe to use them from multiple threads in your app." Hopefully Apple will audit AppKit for concurrency issues more thoroughly sometime soon.

Upvotes: 2

Related Questions