1
votes

The following paragraph from the section on Interoperability of the Using Swift with Cocoa and Objective-C (Swift 2.1) documentation seems to suggest that there is a way to use a Swift class that does not inherit from an Objective-C class for interoperability.

When you create a Swift class that descends from an Objective-C class, the class and its members—properties, methods, subscripts, and initializers that are compatible with Objective-C—are automatically available from Objective-C. In some cases, you need finer grained control over how your Swift API is exposed to Objective-C. You can use the @objc attribute if your Swift class doesn’t inherit from an Objective-C class, or if you want to change the name of a symbol in your interface as it’s exposed to Objective-C code.

And I attempted the following:

import Foundation

@objc class FooBar {
    @objc var name: String;
    init() {
        name = "Hello World!"
    }
}

But unfortunately, it gives a compilation error: Only classes that inherit from NSObject can be declared @objc

Am I misinterpreting something?

1

1 Answers

2
votes

Take a look at this thread on the Apple Developer Forums.

Basically what you say was possible in Xcode <=6, but removed on Xcode 7

Pretty much yes. @objc on Swift-rooted classes never quite behaved like an NSObject-rooted class, leading to various weirdness in the generated header and at runtime. You can still treat any Swift class instance as an AnyObject, mark methods and properties on a Swift class as @objc, and conform to Objective-C protocols; the class just isn't exposed in the generated header and doesn't default to having its members available in Objective-C.