in XCode objective-C game project, how to include a .swift file with constants delcared in it - ios

I have a game in Objective-C and I have constant in it declared like this, in file GameplayConstants.h:
#ifndef GameplayConstants_h
#define GameplayConstants_h
static float REGULAR_TIME_PER_FRAME = 0.1f;
#endif /* GameplayConstants_h */
I am converting game to swift, so I want to convert one by one file to swift. In particular, I want this constant (REGULAR_TIME_PER_FRAME) converted to a swift file, to a constant variable in a swift file GameplayConstants.swift (rather than in the GameplayConstants.h file which it currently sits in now). What should I do? I set the defines module in configuration file to YES, and I included the file (with line include GameplayConstants.swift), but I have various errors. At the moment, error is:
"missing #end"
in HeroAnimationhelper.m file, which has code (partial code displayed):
#import "HeroAnimationHelper.h"
#import "HeroConstants.h"
#import "dealer-Swift.h"
#implementation HeroAnimationHelper
//#include "GameplayConstants.h"
#include "GameplayConstants.swift"
As you see, I'm replacing the original .h file with .swift file.
What else do I need to do to use swift constants in a objective-c class?

Related

How to bridge Objective-C++ code to Swift when we have C++ classes as parameters in header files?

I'm trying to call C++ methods from Swift, and what I've learnt is that I can wrap the C++ stuff to an Objective-C++ class first, then export this Objective-C++ class to Swift. Here's my code:
// CPPClass.h
class CPPClass {
int data;
};
// OCClass.h
#import "CPPClass.h"
#interface OCClass : NSObject
- (instancetype)initWithCPPObject:(CPPClass &)obj;
#end
// MyProject-Bridging-Header.h
#import "OCClass.h"
When I build the project, the compiler throws an Expected a type error in OCClass.h. If I comment out the header file in MyProject-Bridging-Header.h, everything becomes fine, except that I can't use it in Swift any more.
I can solve it by replacing the specific C++ type parameter with a void * pointer, and in this case I can freely use CPPClass in OCClass.mm file, but I wonder if there's any more elegant solutions?

How to compile .h file which has struct definition with default values [duplicate]

This question already has an answer here:
Force Header Files to Compile as C++ in Xcode
(1 answer)
Closed 2 years ago.
I'm trying to use a 3rd party sample code as part of my Objective-C application.
However, when trying to compile my project I get a lot of compiler errors.
The objc syntax that is used in the sample is quite strange and I believe that it is compiled as something else within the project.
For example, as part of the header file the struct definition has default values:
File.h
struct Options
{
int count = 100;
}
...
In their project, the above header file would compile just fine, but when I try to compile it I see an Xcode error:
Expected ';' at end of declaration list
I'm not an objective-c expert, but from what I've read and also found as part of other posts data types cannot have default values, but somehow it compiles fine in the Xcode sample app.
Please let me know if you need more info or other examples of what would compile fine in their project and doesn't work when I copy and paste the code into mine.
Edit:
Force Header Files to Compile as C++ in Xcode
Individually header files doesn't compiled. Compiled source files where they included. If you include them in .c they will be compiled like C, if in .m - like Objective-c, if in .cpp - like C++, if in .mm - like Objective-C++.
My issue was that I was using this header file into a .m file which compiles it to an Objective-C standard. When I change the extension to .mm everything worked fine.
When you think of objective-C as actually being C its more clear why defaults are not set in .h files
This does not apply to the rules of default sizes which are needed when no flexible memory allocation for a data type is available by default, like for (as is) most data types in C.
Even this two sentences already show the difficulty to distinguish what is meant with "default".
Which is why you end up with definition of initiation processes and functions to declare what exactly is "default" in the other file.
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
int count;
} Options;
typedef struct {
int foo;
Options bar[100];
} Foo;
struct Bar {
Foo lotsof;
}
void MyInitiationFunction(Bar *b);
// definition of MyInitiationFunction in .m/.c file
#ifdef __cplusplus
}
#endif
but there is the concept of enum that can trick your mind where defined enumeration default states are what you build some stuff on, which is not a value.

Swift framework - Use Swift class reference in Objective-C class

I am creating Swift framework in which I have to use Objective-C class. So I went through this link. This is the public header of my framework :
#import <UIKit/UIKit.h>
//! Project version number for Test.
FOUNDATION_EXPORT double TestVersionNumber;
//! Project version string for Test.
FOUNDATION_EXPORT const unsigned char TestVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <Test/PublicHeader.h>
#import <arpa/inet.h>
#import <ifaddrs.h>
#import <netdb.h>
#import <sys/socket.h>
#import <MyTest/MPAppDelegateProxy.h>
Now in class MPAppDelegateProxy, I have to use a Swift class which I have created. This is :
#import "MPAppDelegateProxy.h"
#import "MyTest.h"
#implementation MPAppDelegateProxy
+ (void)proxyAppDelegate {
[MPGlobal MPLog:#"App delegate not set, unable to perform automatic setup." file:#"MPAppDelegateProxy.m" function:#"proxyAppDelegate" line:32];
// rest of code
}
MPGlobal is one of my Swift class. But I am getting :
Use of undeclared identifier 'MPGlobal'
Note : I have added #objC before MPGlobal.
You need to import <Target>-Swift.h file.
This is known as Objective-C Generated Interface Header Name.
You can find it in your Target's build settings.
This file is auto generated by compiler and it needs to be imported in Objective-C files.
change the SWIFT_OBJC_INTERFACE_HEADER_NAME build setting and making it the same across different targets. To do so change the instruction that generates this property from $(SWIFT_MODULE_NAME)-Swift.h to $(PROJECT_NAME)-Swift.h as explained here
After doing this Clean Build Folder by pressing Alt and going into Product menu. Since name of header is shared among targets now it can be imported once in the .m ObjectiveC file and all targets can benefit from Swift classes.
If after building it still shows the error, ensure that the header can be reached from XCode by Cmd clicking on its name. It should open a file that contains code similar to this:
SWIFT_CLASS("_TtC27ProjectName_Summary11MyClass")
#interface MyClass : NSObject
- (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER;
#end
If need to ensure that those headers are being generated open a terminal and use this command
find ~/Library/Developer/Xcode/DerivedData -name "*Swift.h"
You should see one header for each target
Another issue that happened to me after those changes is that it started giving errors on ObjectiveC code that I didn't touch. The problem was due to the position of the import, as reported here:
Exactly where at the top of a .m file you #import the hidden bridging
header can make a difference. The usual sign of trouble is that you
get an “Unknown type name” compile error, where the unknown type is a
class declared in Objective-C. The solution is to #import the .h file
containing the declaration for the unknown type in your Objective-C
files as well, before you #import the hidden bridging header. Having
to do this can be an annoyance, especially if the Objective-C file in
question has no need to know about this class, but it resolves the
issue and allows compilation to proceed.
At the very end the code compiles and runs on device and simulator!
Original answer
Also you can try this,
You needed to import the -Swift.h for for both the framework and the app target
For Example :
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#import <Foundation/Foundation.h>
#import "XLPagerTabStrip-Swift.h"
#import "RealmSwift-Swift.h"
...... // Add all frameworks, subclasses, and dependance ios frameworks
#import "MyProject-Swift.h"
You can read this article How to import file header and check paths

Project-Swift.h file not found

I have a new Swift project with a few files, I've needed to add some Objc code.
In Build Settings, my Objective-C Generated Interface Header Name is MyProject-Swift.h
Product Module Name and Product Name are both MyProject.
My Objective-C Bridging Header is MyProject/MyProject-Bridging-Header.h
The contents of my Bridging Header are:
#ifndef MyProject_Bridging_Header_h
#define MyProject_Bridging_Header_h
#import "Blakey.h"
#endif
Blakey.h is pretty simple:
#import Foundation;
#import "MyProject-Swift.h"
#class KeyPair;
#interface Blakey: NSObject
- (void)createKeyPairForSeed:(NSString *)seed;
#end
And Blakey.m
#import <Foundation/Foundation.h>
#import "Blakey.h"
#implementation Blakey
- (void)createKeyPairForSeed:(NSString *)seed;
{
}
#end
(side note: I'm aware my function returns a void, that will be changed later once this issue is fixed so it returns an actual value)
Why is Xcode throwing an error at the #import "MyProject-Swift.h" in Blakey.h?
Project-Swift.h is a file auto generated by Xcode on successful compilation of the project. Catch here is the word successful compilation If your project has any compilation error Project-Swift.h file will not be generated. So in a way it becomes a deadlock. Bestway comment out all the lines that have compilation error and then manage to get it compile without any errors. Only after that Project-Swift.h will be generated.
Additional information, Once the Project-Swift.h file is generated if you open it and if you happened to see that your swift class is not imported there thats because Project-Swift.h imports only the classes that extends from NSObject So plain Swift classes will not be imported.
ISSUE:
You need to import Project-Swift.h in .m file and not .h file. So modify your Blakey as
#import <Foundation/Foundation.h>
#import "Blakey.h"
#import "MyProject-Swift.h"
#implementation Blakey
- (void)createKeyPairForSeed:(NSString *)seed;
{
}
Finally remove #import "MyProject-Swift.h" from Blakey.h
#import Foundation;
#class KeyPair;
#interface Blakey: NSObject
- (void)createKeyPairForSeed:(NSString *)seed;
#end
I had similar issue and almost ended up spending a whole day trying to figure out what wrong with my app.
So following the solution that's helped me :
Clear derived data
Create a class in swift with prefix of #objc for example #objc class mySwiftClass{...}
Build the project again
Et voila.. Should work now.
Why to add #objc?
this #objc prefix, tells the compiler to generate to your swift class a header file. it will add it to the "MyModule-Swift.h" file
I realize this is an old thread, but I had similar issues after adding a new target to a project. I solved it by adding a preprocessor macro (Build Settings -> Apple Clang - Preprocessing) only in said target and then importing the Swift.h file conditionally, like this:
#if DEV_VERSION
#import "Project_DEV-Swift.h"
#else
#import "Project-Swift.h"
#endif
My main target is called Project and the new target is Project DEV (the space is replaced with an underscore in the import), and the preprocessor macro is called DEV_VERSION.
After doing this, both targets build just fine.
<product_name>-Swift.h file not found
It is a kind of bridge(adapter) between Swift and Objective-C. This file contains Swift's API for Objective-C which was marked [#objc and #objcMembers].
You can work with types declared in Swift from within the Objective-C code in your project by importing an Xcode-generated header file.
The header's name is generated from a <product_name>-Swift.h
[Mixing Objective-C and Swift ]
I had a similar issue whereby it would have this issue for anything other than live.
I resolved the issue by hardcoding "Product module name" & "Product name" to my project name. This avoids the need to have preprocessor logic in every file that includes swift code as demonstrated in Pauli Kettunen's solution.

Xcode 8 (Swift): core.hpp header must be compiled as C++

I am using the OpenCV iOS Framework in a project. I followed the necessary steps to include the framework into the project.
The Project is written using Swift 3.
One of my classes that contains the core functionality of the App is written in Objective-C++. I included the header of the class in my Bridge-header file but when trying to run the project I get the following error:
error core.hpp header must be compiled as C++
After researching online and on SO, the most common solution presented was to create a Wrapper class that would be imported in the bridge header. However, after following this article I face the same problem.
The Header file of my class looks like this:
#if TARGET_OS_IPHONE
#import <UIKit/UIKit.h>
#define IMAGE_CLASS UIImage
#elif TARGET_OS_MAC
#import <Cocoa/Cocoa.h>
#define IMAGE_CLASS NSImage
#endif
#import <AGGeometryKit/AGKQuad.h>
#import <stdio.h>
#import <opencv2/opencv.hpp>
#import <Foundation/Foundation.h>
typedef void (^DebugBlock)(cv::Mat current_image, std::string current_image_name);
#interface ImageScanner : NSObject
/**
* Singleton for access to the scanner.
*
* #return Shared scanner.
*/
+ (instancetype)sharedScanner;
Does anyone have an idea what I might be missing?
Thank you in advance!
G.
had the same problem.. solved by importing any file that use openCV in the wrapperClass.mm file ...
SO Answer here

Resources