在Objective-C中如何使用带有inout参数的Swift方法?

use*_*500 15 objective-c swift

我想要

func foo(inout stop: Bool) -> Void {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

在我的Objective-C部分中使用.但它永远不会在Module-Swift.h头文件中生成.如果我用@objc标记它,那么

方法不能标记为@objc,因为参数的类型不能在Objective-C中表示

发生错误.

Mik*_*e S 23

你不能使用inout与Objective-C的桥接时参数,但如果您使用的是你可以做同样的事情UnsafeMutablePointer<T>(TBool你的情况).它看起来像这样:

@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
    }
}
Run Code Online (Sandbox Code Playgroud)

TestClass.swift:

public class TestClass: NSObject {
    @objc func foo(stop: UnsafeMutablePointer<Bool>) -> Void {
        stop.pointee = true
    }
}
Run Code Online (Sandbox Code Playgroud)

Objective-C的:

TestClass *test = [[TestClass alloc] init];
BOOL stop = false;
[test foo:&stop];
// stop is YES here
Run Code Online (Sandbox Code Playgroud)

  • 如何将 UnsafeMutablePointer 从 swift 传递到 Objective-C? (2认同)