I have an Objective-C method that accepts a parameter of type id
and I want to pass it a Swift struct.
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 compile error message I get:
Type 'DemoStruct' does not conform to protocol 'AnyObject'
So my question would be, how do I make an Objective-C method accept Any
instead of AnyObject
and is there such a thing?
Swift Struct is not available in Objective-C. Enum only Int types are available in Objective-C. Swift functions with default parameter values are available in Objective-C but you will have to give values to each parameter.
Structs can be passed by reference using the inout keyword and the & operator. This practice is discouraged unless you can prove it's the only way to get the performance you need in a critical situation. Note that you won't save the burden of copying the UIImage by doing this.
Import Swift code into Objective-C within the same framework: Under Build Settings, in Packaging, make sure the Defines Module setting for that framework target is set to Yes. Import the Swift code from that framework target into any Objective-C .
You can use regular C structs all you want. Your example tries to put references to an Objective-C object, NSString , into a struct , which is incompatible with ARC. Structs are typically used for simple data structures. Examples that you are likely to come across in Objective-C code are CGPoint and CGRect .
The best thing i found was to wrap in a Box class
public class Box<T> {
let unbox: T
init(_ value: T) {
self.unbox = value
} }
You can't do it.
Swift structs are not accessible from Objective-C. This is stated in the "Using Swift With Cocoa and Objective-C" book from Apple:
You’ll have access to anything within a class or protocol that’s marked with the @objc attribute as long as it’s compatible with Objective-C. This excludes Swift-only features such as those listed here:
- Generics
- Tuples
- Enumerations defined in Swift
- Structures defined in Swift
- Top-level functions defined in Swift
- Global variables defined in Swift
- Typealiases defined in Swift
- Swift-style variadics
- Nested types
- Curried functions
Excerpt From: Apple Inc. “Using Swift with Cocoa and Objective-C.” iBooks. https://itun.es/gb/1u3-0.l
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With