Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift compiling bug "Unknown type name" and "Expected a type"

Tags:

ios

swift

I'm running into an issue where my Swift code compiles fine but then the generated -Swift.h file has an error in it...

Here is an example of what I'm doing:

class MyScene : CCLayer {
    var ctrl : CCControlSlider?
}

This compiles just fine in the swift code and I can see the methods on the ctrl object just fine as well. I have the following in my bridge header:

#import "cocos2d.h"
#import "CCControlSlider.h"

This works perfectly fine in other classes that use other libraries which work correctly. Also note that I can use this CCControlSlider class in my objective-c classes with no issues at all as well.

Here is what happens on the generated -Swift.h file:

SWIFT_CLASS("_TtC15MyProject10MyScene")
@interface MyScene : CCLayer
@property (nonatomic) CCControlSlider * ctrl;
@end

The property has the error "Unknown type name "CCControlSlider" and if it's used in a method then it gives the error "Expected a type".

This works just fine using other classes but for some reason this one class gives this compiler error only in the generated header file and only when used from Swift.

I guess what I'm wondering is, am I doing something wrong or is this just a bug??

like image 610
Rocky Pulley Avatar asked Jun 11 '14 18:06

Rocky Pulley


2 Answers

The answer given here is the simplest approach: https://stackoverflow.com/a/24216718/341994

Basically, somewhere in your Objective-C code you are importing the automatically generated -Swift.h header. In that same code, before that #import line, insert #import "CCControlSlider.h". The order of these two #import statements is crucial!

The fact that this Objective-C class may not need CCControlSlider is irrelevant (though if it does, that's a bonus). The important thing is the order. We want to expose the namespace to CCControlSlider before exposing the namespace to the automatically generated -Swift.h header.

like image 86
matt Avatar answered Sep 18 '22 12:09

matt


While incorporating a set of Objective C files into my mostly Swift-based project I suddenly started getting a lot of these errors on them. Then I realized though the file had:

#import <Foundation/Foundation.h>

It did not have:

#import <UIKit/UIKit.h>

and once I added that line the errors started resolving. Cleaning afterwards always helps. Good luck

NOTE: With newer versions of Swift imports are much easier to type and are done like so:

import UIKit
like image 39
Chris Klingler Avatar answered Sep 18 '22 12:09

Chris Klingler