Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an Objective-C class from Swift inside a package

I am creating a swift package which needs to use some old Objective-C code that I am not ready to port in Swift right now.

This is my package structure:

- MyPackage
  |
  |-README.md
  |
  |-Package.swift
  |
  |-Sources
    |
    |-MyPackageSwift
    | |
    | |- MyPackage.swift  
    |
    |-MyPackageObj
      |
      |-Include
      | |
      | |- MyObjCClass.h
      |
      |- MyObjCClass.m

This is the Package.swift:


import PackageDescription

let package = Package(
    name: "MyPackage",
    products: [
        .library(
            name: "MyPackage",
            targets: ["MyPackageSwift","MyPackageObj"]),
    ],
    dependencies: [
    ],
    targets: [
        .target(
            name: "MyPackageSwift"
        ),
        .target(
            name: "MyPackageObj"
        ),
    ]
)

The Obj-C class is:

//
//  MyObjCClass.h
//  
#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface MyObjCClass : NSObject
- (NSString *)myObjCService;
@end

NS_ASSUME_NONNULL_END

and:

//
//  MyObjCClass.m
//  
#import "MyObjCClass.h"

@implementation MyObjCClass

- (NSString *)myObjCService {
    return @"This is myObjCService";
}
@end

My problem is that since I cannot use the bridge file I don't know how to make the Objective-C class visible from the Swift code:


public struct MyPackage {

    public init() {
    }
    
    public func myService() -> String {
        
        let objcService = MyObjCClass()
        
        return "This is myService in MyPackage"
    }
}

and I get this error:

Cannot find 'MyObjCClass' in scope

like image 295
Fab Avatar asked Oct 19 '25 20:10

Fab


1 Answers

I eventually found the way to make it working. These are the required changes:

  1. Package.swift

...

.target(
            name: "MyPackageSwift",
            dependencies: ["MyPackageObj"] <-----
        ),

...

  1. MyPackage

import MyPackageObj <-----

public struct MyPackage {

    public init() {
    }
    
    public func myService() -> String {
        
        let objcService = MyObjCClass()
        
        return "This is myService in MyPackage " +  objcService.myObjCService()
    }
}


like image 80
Fab Avatar answered Oct 21 '25 09:10

Fab