如何将Swift结构作为参数传递给Objective-C方法

前端之家收集整理的这篇文章主要介绍了如何将Swift结构作为参数传递给Objective-C方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个Objective-C方法接受id类型的参数,我想传递一个 Swift结构.

ObjcClass.m文件

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

DemoStruct.swift文件

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

我得到的编译错误消息:

Type ‘DemoStruct’ does not conform to protocol ‘AnyObject’

所以我的问题是,如何使Objective-C方法接受Any而不是AnyObject并且有这样的事情?

你不能这样做.

从Objective-C无法访问Swift结构.这在Apple的“使用Swift With Cocoa和Objective-C”一书中有所说明:

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

摘录自:Apple Inc.“将Swift与Cocoa和Objective-C结合使用.”iBooks. https://itun.es/gb/1u3-0.l

原文链接:https://www.f2er.com/swift/319563.html

猜你在找的Swift相关文章