加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 05:33:13 所属栏目:百科 来源:网络整理
导读:我有一个Objective-C方法接受id类型的参数,我想传递一个 Swift结构. ObjcClass.m文件: @implementation ObjcClass+ (void)addListener:(id)listener { // Do something with listener} DemoStruct.swift文件: struct DemoStruct { func registerAsListener
我有一个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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读