如何在Objective-C中使用带有inout参数的Swift方法? [英] How can method in Swift with inout parameter be used in Objective-C?
问题描述
我想要
func foo(inout stop: Bool) -> Void {
// ...
}
在我的 Objective-C 部分使用.但它永远不会在 Module-Swift.h 头文件中生成.如果我用@objc 标记它,
use in my Objective-C part. But it is never generated in Module-Swift.h header. If I mark it with @objc, the
方法不能被标记@objc 因为参数的类型不能用 Objective-C 表示
Method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C
发生错误.
推荐答案
在与 Objective-C 桥接时,您不能使用 inout
参数,但是如果您使用 inout
参数,则可以执行类似的操作code>UnsafeMutablePointer<T>(在您的情况下,T
将是 Bool
).它看起来像这样:
You can't use an inout
parameter when bridging with Objective-C, but you can do something similar if you use an UnsafeMutablePointer<T>
(T
would be Bool
in your case). It would look something like this:
@objc func foo(stop: UnsafeMutablePointer<Bool>) -> Void {
if stop != nil {
// Use the .pointee property to get or set the actual value stop points to
stop.pointee = true
}
}
<小时>
示例
TestClass.swift:
Example
TestClass.swift:
public class TestClass: NSObject {
@objc func foo(stop: UnsafeMutablePointer<Bool>) -> Void {
stop.pointee = true
}
}
目标-C:
TestClass *test = [[TestClass alloc] init];
BOOL stop = false;
[test foo:&stop];
// stop is YES here
这篇关于如何在Objective-C中使用带有inout参数的Swift方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!