How to extend Objective-C class with Swift in framework?

I have an (OS X) Objective-C framework to which I want to add some Swift extensions, and I'm using Xcode 7ß6 to work with this. There is a class in the structure (let it be called "Sample"), implemented in the files "Sample.h" and "Sample.m" .. "Sample.h" contains:

#import <Foundation/Foundation.h> @interface Sample : NSObject @property int x; @end 

.. and "Sample.m" contains:

 #import "Sample.h" @implementation Sample - (instancetype) init { if ((self = [super init]) == nil) return nil; self.x = 99; return self; } @end 

I added "Sample.swift" to a framework containing:

 import Foundation extension Sample { func PrettyPrint () { print("\(x)") } } 

This is clearly a trivial version of what I want to do in a wider context, here I want to use the Swift file for the "Sample" extension by adding the "PrettyPrint" function.

.. the framework builds without errors, but the "PrettyPrint" framework function is not displayed to the calling application. Application code calling into the framework like:

 import Foundation import TestKit let sample = Sample() sample.PrettyPrint() 

fails "sample.PrettyPrint ()" with: A value of type "sample" does not have a member of "PrettyPrint"

Why is this failing? and is it possible to make work?

Additional information: if I delete the file "Sample.swift" from the framework and put its application, which is called into the framework, the "Sample" class is successfully expanded and "sample.PrettyPrint ()" works as expected (printing "99").

+8
objective-c frameworks swift2
source share
2 answers

Have you tried to make the extension and feature public?

 public extension Sample { public func PrettyPrint () { print("\(x)") } } 
+9
source share

In this example, if there is a method in

Sample.m:

 - (void)PrettyPrintObjC { NSLog(@"This is from ObjC"); } 

As you call it from Sample.swift:

 public extension Sample { public func PrettyPrint () { print("\(x)") PrettyPrintObjC() // This does not work } } 
0
source share

All Articles