Ramsay Consulting Ramsay Consulting - 8 days ago 5
Objective-C Question

How to extend an Objective-C class with Swift in a 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 class in the framework (let's call it "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 have added "Sample.swift" to the framework containing:

import Foundation

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


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

.. the framework builds without error, but the framework function "PrettyPrint" is not visible to a calling app. App code calling into the framework like:

import Foundation
import TestKit

let sample = Sample()
sample.PrettyPrint()


fails on "sample.PrettyPrint()" with: Value of type 'Sample' has no member 'PrettyPrint'

Why does this fail? and Can it be made to work?

Extra info: If I remove the file "Sample.swift" from the framework and place it the app which is calling into the framework, the "Sample" class is successfully extended and "sample.PrettyPrint()" works as expected (printing "99").

Answer

Have you tried making the extension and function public?

public extension Sample {
    public func PrettyPrint () {    
        print("\(x)")
    }
}
Comments