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

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

ObjcClass.m文件

  1. @implementation ObjcClass
  2. + (void)addListener:(id)listener {
  3. // Do something with listener
  4. }

DemoStruct.swift文件

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

我得到的编译错误消息:

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

猜你在找的Swift相关文章