Is there a way to use Swift structs in Objective-C without making them Classes?

Viewed 9399

I have several simple structs written in swift inside .swift files. These structs are very simple and contain almost only Strings:

struct Letter {
   struct A {
      static let aSome : String = "descASome"
      static let aSomeMore : String = "descASomeMore"
   }
   struct B {
      static let bNow : String = "descBNow"
      static let bLater : String = "descBLater"
   }
...
}

I want to use those structs inside a project which contains Objective-C code because I'm writing a cross platform framework.

I have read: ObjectiveC - Swift interoperability by Apple which clearly states that Swift written structs can't be used by ObjectiveC. Excluded are (among other features):

Structures defined in Swift

Solution 1:

I have found a SO solution which solves the issue by using classes:

@objc class Letter : NSObject {
   @objc class A : NSObject {
      static let aSome : String = "descASome"
      static let aSomeMore : String = "descASomeMore"
   }
   @objc class B : NSObject {
      static let bNow : String = "descBNow"
      static let bLater : String = "descBLater"
   }
...
}

This solution works, however I have to rewrite all the structs to classes. They are also not lightweight like structs (among other things). Besides I feel like I am going backwards to solve the problem.

Q1. Is there any other way to use Swift structs inside ObjectiveC beside solution 1 which doesn't fit well for my project/situation? (enums can be used if their rawValue is Int)

Q2. Is there a way to use #define SomeConst for ObjectiveC access and stucts for Swift access like :

#if macOS // if Swift?
#endif
2 Answers

As of now, NO. You will need Classes to store model objects.

@objcMembers public class Car: NSObject {
    public var mileage: NSNumber?
}

@objcMember virtually converts them to Objective-c readable format and can be accessed from Objective-C classes. This will make your code interoperable.

Note: Make sure the class type is NSObject.

Related