@objc attribute & Windows

Both @objc and @objcMembers attributes break compilation on Windows. I tried to wrap them in #if canImport(Darwin) but that breaks declaration. What is the preferred way to port existing sources what use these attributes on non-Darwin platforms?

1 Like

It is a bug. Those attributes are properly ignored on Linux, Android and web. Windows is supposed to as well. It does so in some contexts, but has been know to fail in others. If you have found such context, report it here: bugs.swift.org.

This is the proper way to use @objc in cross‐platform code:

@objc func doSomething() {}

In instances where that triggers a bug, this is how I work around it:

#if os(Windows)
  func doSomething() { _doSomething() }
  @objc func doSomething() { _doSomething() }
private func _doSomething() {
  // ...

Unfortunately, In my case it is a type declaration.

I filled a bug report https://bugs.swift.org/browse/SR-14381


Was a proposal ever suggested to allow surrounding attributes with #if #endif, such as

#if canImport(Darwin)
class MyClass {}

Allowing this syntax would solve this issue.

This is definitely the wrong check. The check should be #if canImport(ObjectiveC).

I don't believe that Windows has any special paths for the @objc handling and it should be the same as other platform with -disable-objc-interop.

I added some thoughts on a related JIRA. https://bugs.swift.org/browse/SR-14548?focusedCommentId=63529&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-63529

Having the attribute be ignored on Linux [and Windows here] for classes and protocols would require a Swift evolution proposal [earlier, they were ignored due to a bug, not intentionally]. You could submit a small evolution pitch for that. If that gets some momentum, you could submit a proposal with an implementation.

Another option is a Swift evolution pitch for more flexible usage around attributes. In [Accepted] SE-0308: postfix `#if` config expressions, it says

The core team believes that additional refinement of conditional compilation is something that the language would benefit from. As such, proposals extending support towards conditional compilation of repeated lexical constructs, e.g. elements within an array literal, would be welcome.

They were ignored earlier on other platforms (such as Linux) due to a compiler bug. Right now (for Swift 5.5) they are supported for enums but disallowed for classes and protocols.

Even though a bug, if the fix caused previously correctly compiling working code to cease to compile in a point release, seems it’s the fix that should have required a proposal and not the fix for the fix…

Terms of Service

Privacy Policy

Cookie Policy