How can method in Swift with inout parameter be used in Objective-C?

后端 未结 2 897
孤街浪徒
孤街浪徒 2021-02-19 01:18

I want

func foo(inout stop: Bool) -> Void {
    // ...
}

use in my Objective-C part. But it is never generated in Module-Swift.h header. If

相关标签:
2条回答
  • 2021-02-19 01:54

    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
        }
    }
    

    Example

    TestClass.swift:

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

    Objective-C:

    TestClass *test = [[TestClass alloc] init];
    BOOL stop = false;
    [test foo:&stop];
    // stop is YES here
    
    0 讨论(0)
  • 2021-02-19 01:56

    Similarly to what happening with generics, inout is not objc-compatible.

    One possible workaround is to embed your parameter(s) in a class (which is a reference type, hence passed by pointer and not by value):

    @objc class MyFuncParams {
        var stop: Bool
    
        init(stop: Bool) {
            self.stop = stop
        }
    }
    

    and define the function to accept an instance of that class:

    func changeParam(params: MyFuncParams) {
        params.stop = true
    }
    

    Not an elegant way to solve the problem, but what's important is that it should work (never tried myself though).

    0 讨论(0)
提交回复
热议问题