I read the article here... https://developer.apple.com/documentation/swift/imported_c_and_objective-c_apis/importing_swift_into_objective-c
and this is what I did.
- Created a header file for swift file.
- added @class SwiftFile.h
- #import MyAppTargetName-Swift.h in the objc file from where I want to reference my swift code.
Now in my swift file when I write...
@interface ClassName
{
MySwiftClass *swiftClass;
}
I get error message Unknown Type Name "MySwiftClass".
How can I resolve this and get going?
Am I doing something wrong?
Does the bridging header i created along with the swift file need to me edited?
Neerav
I’m honestly not sure how you managed to get into the state you’ve got into. It’s hard to debug such problems without having access to your project. As an alternative, I’ve included working instructions below. Please try repeating this at your end. That’ll help in one of two ways:
If they don’t work, there’s something wonky in your environment.
If they do work, you have a working example that you can compare against your main project.
Here’s what I did:
In Xcode 11.3, I created a new app from the macOS > App template. I named it MyApp, set the language to Objective-C, and the UI to Storyboard.
In the Project navigation on the left, I selected
and then chose File > New > File.main.m
I selected the macOS > Swift template and named the file
.MySwiftClass.swift
After saving the file, Xcode asked me whether I wanted to create a bridging header. I clicked Create Bridging Header. This isn’t necessary for this task, but you’ll likely need it later and it’s best to do it at this point.
I change
to look like this:MySwiftClass.swift
import Foundation @objc class MySwiftClass: NSObject { @objc func run() { print("MySwiftClass.run \(Date())") } }
.
In the Project navigation on the left, I selected
again.main.m
I added this line after the existing
:#import
#import "MyApp-Swift.h"
.
Inside the
I added this code:@autoreleasepool
MySwiftClass * obj = [[MySwiftClass alloc] init]; [obj run];
.
I ran the app. It printed:
MySwiftClass.run 2020-02-20 10:37:03 +0000
.
Share and Enjoy
—
Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
let myEmail = "eskimo" + "1" + "@apple.com"