Home > Enterprise >  What is the proper syntax for accessing a function from ObjC to a Swift Package?
What is the proper syntax for accessing a function from ObjC to a Swift Package?

Time:09-26

Simple Scenario: I want to call any Swift Package member function from within Objective-C.

I'm building a reference/demo/proof-of-concept app to mix ObjC with Swift.

Here's a working snippet from the Swift side:

import Foundation
import RicPackage

final class Greetings: NSObject {
    @objc public static let shared = Greetings()
    private override init() {}
    
    @objc public func doSomething(name: String) {
        print("Do something, \(name)")
        let ricClass = RicClass()
        ricClass.sayHello()
    }
    
    @objc public func hello() {
        print("Hello Everybody!")
    }
}

Here's the Objective-C side:

#import "ViewController.h"
#import "ObjcSwiftHeader-Swift.h"

@class RicClass;

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"Inside VC ViewDidLoad.");
    Greetings *greetings = [Greetings shared];
    [greetings hello];
    [greetings doSomethingWithName: @"Ric"];
    
    RicClass *ricClass = [RicClass alloc];
}


@end

I got this compiler error:

enter image description here

Here's the snapshot of the project:

enter image description here

Here's the Swift Package stuff:

import Foundation

public struct RicStruct {
    public private(set) var text = "Hello, World!"

    public init() {
    }
    
    public func sayHello() -> String {
        "Hello Ric!"
    }
}

public class RicClass: NSObject {
    @objc public var msg = "Mother has a feeling, I might be too appealing."
    @objc public let text = "Hello Everybody!"
    
    public override init() {}
  
    public func sayHello() {
            print(text)
        }
    
    public func doSomething() {
        print("Inside doSomething()")
    }
}

There must be a simple solution....

CodePudding user response:

Packages are linked as dynamic embedded frameworks into your app and to use them you should import a package's library to your source file:

Swift:

import RicPackage

Objective-C:

@import RicPackage;
  • Related