How to pass a Swift structure as a parameter to an Objective-C method

I have an Objective-C method that takes a type parameter id, and I want to pass a Swift structure to it.

ObjcClass.m file:

@implementation ObjcClass
+ (void)addListener:(id)listener {
    // Do something with listener
}

DemoStruct.swift file:

struct DemoStruct {
    func registerAsListener() {
        ObjcClass.addListener(self) // Can't find a way to do this
    }
}

The compilation error message I get:

The type "DemoStruct" does not comply with the protocol "AnyObject"

So my question is: how to make an Objective-C accept method Anyinstead AnyObjectand is there such a thing?

+8
source share
2 answers

The best I have found is to wrap the Box class

public class Box<T> {
    let unbox: T
    init(_ value: T) {
        self.unbox = value
    } }
+11
source

You cannot do this.

Swift lines are not available from Objective-C. This is stated in Apple’s book Using Swift With Cocoa and Objective-C:

- , @objc, Objective-C. Swift, :

  • , Swift
  • , Swift
  • , Swift
  • , Swift
  • , Swift
  • Swift

: Apple Inc. " Swift Cocoa Objective-C." . https://itun.es/gb/1u3-0.l

+11

Source: https://habr.com/ru/post/1695519/


All Articles