如何将Swift数组传递给Objective-C函数

coy*_*yer 2 objective-c swift

我想将一组CGPoint值传递给另一个Objective-C函数.

迅速:

var myPoints:[CGPoints]? = [CGPoint(x: 0, y:0)]
ObjCWrapper.callSomething(&myPoints)
Run Code Online (Sandbox Code Playgroud)

Objective-C的

+ (void) callSomething: (CGPoint []) points {...}
Run Code Online (Sandbox Code Playgroud)

我得到的错误:

Cannot invoke 'callSomething' with an argument list of type 'inout [CGPoint]?)'
Run Code Online (Sandbox Code Playgroud)

Air*_*ity 6

问题是你做了myPoints可选的,即[CGPoint]?代替[CGPoint].从您的代码片段中,您不清楚为什么要这样做.如果不需要更广泛的上下文,只需删除?并编译此代码即可.

注意,如果ObjCWrapper.callSomething是您编写和控制的函数,如果const CGPoint []实际上不需要更改数组中的值,请考虑使用它.这样,它不会是inout这样你不需要&在前面myPoints,你也可以使用它,如果它声明let,即:

// no need to give a type, it can be inferred as [CGPoint]
let myPoints = [CGPoint(x: 0, y:0)]
ObjCWrapper.callSomething(myPoints)
Run Code Online (Sandbox Code Playgroud)

如果你声明为:

+ (void) callSomething: (const CGPoint []) points {...}
Run Code Online (Sandbox Code Playgroud)

另一方面,如果出于未显示的原因,它确实需要是一个可选数组,您将不得不使用一些解包技术来获取底层指针而不是使用隐式互操作支持:

let myPoints: [CGPoint]? = [CGPoint(x: 0, y:0)]
myPoints?.withUnsafeBufferPointer { buf->Void in
    ObjCWrapper.callSomething(buf.baseAddress)
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您无法更改callSomething为采用const数组,则会非常烦人:

var myPoints: [CGPoint]? = [CGPoint(x: 0, y:0)]
myPoints?.withUnsafeMutableBufferPointer {
  (inout buf: UnsafeMutableBufferPointer)->Void in
    ObjCWrapper.callSomething(buf.baseAddress)
}
Run Code Online (Sandbox Code Playgroud)