Skip to content

Instantly share code, notes, and snippets.

@justAnotherDev
Created February 23, 2016 23:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justAnotherDev/78483f9d94e40fd90c38 to your computer and use it in GitHub Desktop.
Save justAnotherDev/78483f9d94e40fd90c38 to your computer and use it in GitHub Desktop.
ClassA does not work as expected, ClassB does. Sample code for: http://stackoverflow.com/questions/35590015/swift-objc-circular-import
//
// Use this file to import your target's public headers that you would like to expose to Swift.
//
#import "XXClassC.h"
//
// ClassA+B.swift
//
import Foundation
/**
Create contrived class that is named XXClassA in ObjC and ClassA in Swift.
*/
@objc(XXClassA) class ClassA: NSObject {
let foo = "bar"
}
/**
Create contrived class that is named XXClassB in ObjC and Swift.
*/
class XXClassB: NSObject {
let foo = "bar"
}
extension ClassA {
/**
Attempt to instantiate XXClassC (which has a reference to XXClassA) from Swift fails.
-Note: Implemented in extension for clarity of post, but same issue arises if part of main class.
*/
func useClassC() {
let someVar1 = XXClassC(a: XXClassA()) // Error: use of unresolved identifier 'XXClassA'
let someVar2 = XXClassC(b: XXClassB()) // works
}
}
//
// XXClassC.h
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@class XXClassA, XXClassB;
@interface XXClassC : NSObject
-(instancetype)initWithA:(XXClassA *)classA;
-(instancetype)initWithB:(XXClassB *)classB;
// mark default init as unnavailable
-(instancetype)init __attribute__((unavailable));
@end
NS_ASSUME_NONNULL_END
//
// XXClassC.m
//
#import "XXClassC.h"
#import "CircularImports-swift.h"
NS_ASSUME_NONNULL_BEGIN
@implementation XXClassC
- (instancetype)initWithA:(XXClassA *)classA {
NSLog(@"%@", classA.foo);
return [super init];
}
- (instancetype)initWithB:(XXClassB *)classB {
NSLog(@"%@", classB.foo);
return [super init];
}
@end
NS_ASSUME_NONNULL_END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment