I'd created a test project to try Swift. But I've stuck on importing Swift class into Objective-C class. Project name is "TestSwift1". And I have set Defines Module in Packaging to YES. XCode-Beta3
I have next code:
//swift SwtClass.swift
import Foundation
class SwtClass
{
var title = ""
}
//Objective-C ObjClass.h
@interface ObjClass : NSObject
@property (nonatomic, strong) NSString* title;
@end
//Objective-c ObjClass.m
#import <Foundation/Foundation.h>
#import "ObjClass.h"
#import <testSwift1-Swift.h>
@implementation ObjClass
- (void)doSomething
{
SwtClass* b; // Error: "Use of undeclared identifier 'SwtClass'"
// Error: "Use of undeclared identifier 'b'"
NSLog(@"something is done");
}
@end
You can work with types declared in Swift from within the Objective-C code in your project by importing an Xcode-generated header file. This file is an Objective-C header that declares the Swift interfaces in your target, and you can think of it as an umbrella header for your Swift code.
To access and use swift classes or libraries in objective-c files start with an objective-c project that already contains some files. Add a new Swift file to the project. In the menu select File>New>File… then select Swift File, instead of Cocoa Touch Class. Name the file and hit create.
You can use 3 techniques to fix the Use of unresolved identifier error in Xcode: Check your code for typos. Search the exact error message. Use autocompletion and Quick Help to find recognized identifiers.
The Swift library cannot be directly called from Objective-C, since it is missing the required annotations in the code, and in many cases, modules do not inherit from NSObject, rather they use the native Swift data types.
While writing this question I've found solution. And as always it was very simple but took a while maybe this will save somebody a couple of minutes.
To use Swift class(that is not a subclass of NSObject) in Objective-C don't forget to mark it with @objc as it said here "Using Swift from Objective-C". My Swift class had to look like this:
//swift SwtClass.swift
import Foundation
@objc class SwtClass
{
var title = ""
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With