Thanks for being a part of WWDC25!

How did we do? We’d love to know your thoughts on this year’s conference. Take the survey here

Objective-C Literals inside a Swift Package

I have a Swift Package that contains an Objective-C target. The target contains Objective-C literals but unfortunately the compiler says "Initializer element is not a compile-time constant", what am I doing wrong?

Based on the error triggering in the upper half, I take it that objc_array_literals is on.

My target definition looks like:

.target(
            name: "MyTarget",
            path: "Sources/MySourcesObjC",
            publicHeadersPath: "include",
            cxxSettings: [
                .unsafeFlags("-fobjc-constant-literals")
            ]
        ),

I believe Objective-C literals are enabled since a long time but I still tried passing in the -fobjc-constant-literals flag and no luck.

To be clear I'm not interested in a run-time initialization, I really want it to be compile time. Does anyone know what I can do?

Answered by DTS Engineer in 839328022

I believe that this feature is only supported if your deployment target is macOS 11 or later. So, to get this working I had to add this to my Package.swift:

platforms: [.macOS(.v11)],

Once I did that, I didn’t to manually add -fobjc-constant-literals via the cSettings parameter.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Not a direct answer, just sharing my experience:

After some Xcode update, I had to replace all @-1 literals with explicit NSNumber initializers like this:

ret.availableScales = @[[NSNumber numberWithInt:-1], @0, @1];

For some reason, @-1 wasn’t being evaluated correctly for my code anymore in some places. I contacted Apple about it, but they couldn’t reproduce the issue at the time with simple code.

Looks like objective-c literals support is more and more lagging behind.

Can you use static/const strings?

I believe that this feature is only supported if your deployment target is macOS 11 or later. So, to get this working I had to add this to my Package.swift:

platforms: [.macOS(.v11)],

Once I did that, I didn’t to manually add -fobjc-constant-literals via the cSettings parameter.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Accepted Answer

Thank you so much Quinn, this solved my problem!

Objective-C Literals inside a Swift Package
 
 
Q