Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Swift class in Objective c. Undeclared identifier error ocurs

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
like image 469
Vitalii Boiarskyi Avatar asked Jul 09 '14 15:07

Vitalii Boiarskyi


People also ask

Can we use Swift class in Objective-C?

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.

How do I add Swift class to Objective-C project?

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.

How do I fix unresolved identifier in Swift?

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.

Can I use Swift library in Objective-C?

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.


1 Answers

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 = ""
}
like image 80
Vitalii Boiarskyi Avatar answered Sep 20 '22 17:09

Vitalii Boiarskyi