将实现协议的Swift类导入到Objective-C类中

时间:2023-01-15 17:52:14

I have a class in Swift that implements a protocol:

我在Swift有一个类,它实现一个协议:

class SwiftClass: SwiftProtocol {
    func test() {
        NSLog("Test");
    }
}

And here is the simple protocol

这是一个简单的协议

@objc protocol SwiftProtocol {
    func test()
}

When I import it and use it an Objective-C class, it gives this error

当我将它导入并使用一个Objective-C类时,它会产生这个错误

Use of undeclared identifier 'SwiftClass'

使用未声明的标识符'SwiftClass'

  1. When I make SwiftClass extend NSObject, it works fine.
  2. 当我使SwiftClass扩展NSObject时,它工作得很好。
  3. Having and removing @objc in the protocol yields the same error.
  4. 在协议中包含和删除@objc会产生相同的错误。
  5. The Target Membership of the 2 files point to the correct project.
  6. 这两个文件的目标成员指向正确的项目。

Is there a way to import my class that implements a protocol? What am I doing wrong?

是否有办法导入实现协议的类?我做错了什么?

1 个解决方案

#1


1  

From https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/InteractingWithObjective-CAPIs.html#//apple_ref/doc/uid/TP40014216-CH4-ID35, section Swift Type Compatibility:

来自https://developer.apple.com/library/content/documentation/swift/buildingcocoaapps/interactingwithobjective - capis.html #/ apple_ref/doc/uid/ tp400216 - ch4 - id35, Swift类型兼容性:

When you create a Swift class that descends from an Objective-C class, the class and its members—properties, methods, subscripts, and initializers—that are compatible with Objective-C are automatically available from Objective-C.

当您创建一个从Objective-C类派生的Swift类时,与Objective-C兼容的类及其成员(属性、方法、下标和初始值)将自动从Objective-C中获得。

This is consistent with what you observed: it works fine if SwiftClass extends NSObject. Is there anything wrong with solving the problem this way?

这与您所观察到的一致:如果SwiftClass扩展NSObject,那么它可以正常工作。用这种方法解决问题有什么问题吗?

#1


1  

From https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/InteractingWithObjective-CAPIs.html#//apple_ref/doc/uid/TP40014216-CH4-ID35, section Swift Type Compatibility:

来自https://developer.apple.com/library/content/documentation/swift/buildingcocoaapps/interactingwithobjective - capis.html #/ apple_ref/doc/uid/ tp400216 - ch4 - id35, Swift类型兼容性:

When you create a Swift class that descends from an Objective-C class, the class and its members—properties, methods, subscripts, and initializers—that are compatible with Objective-C are automatically available from Objective-C.

当您创建一个从Objective-C类派生的Swift类时,与Objective-C兼容的类及其成员(属性、方法、下标和初始值)将自动从Objective-C中获得。

This is consistent with what you observed: it works fine if SwiftClass extends NSObject. Is there anything wrong with solving the problem this way?

这与您所观察到的一致:如果SwiftClass扩展NSObject,那么它可以正常工作。用这种方法解决问题有什么问题吗?