Swift - C API 桥接器 - 如何处理空指针

Mar*_*rry 4 c optional swift

在 Swift 中,我使用 C API 返回带有字符数组的结构(包含 UTF8 空终止字符串或空值)。

struct TextStruct {
   char * text;
   //other data
}
Run Code Online (Sandbox Code Playgroud)

我用:

let text: String = String(cString: data.text)
Run Code Online (Sandbox Code Playgroud)

这有效,但是,当data.textis 时nullptr,这会失败

fatal error: unexpectedly found nil while unwrapping an Optional value
Run Code Online (Sandbox Code Playgroud)

是否有任何解决方法,或者我必须data.text在使用cStringctor之前手动检查?

Mar*_*n R 6

除了Gwendal Roué 的解决方案:您可以 注释C API 以指示指针是否可以为空。例如,

struct TextStruct {
    char * _Nullable text;
    //other data
};
Run Code Online (Sandbox Code Playgroud)

导入到 Swift 中

public struct TextStruct {
    public var text: UnsafeMutablePointer<Int8>?
    // ...
}
Run Code Online (Sandbox Code Playgroud)

其中var text是“强”可选,而不是隐式展开的可选。然后

let text = String(cString: data.text)
// value of optional type 'UnsafeMutablePointer<Int8>?' not unwrapped; ...
Run Code Online (Sandbox Code Playgroud)

不再编译,并强制您使用可选绑定或其他解包技术,并且“致命错误:意外发现 nil” 不会再意外发生。

有关更多信息,请参阅Swift 博客中的“Nullability and Objective-C” ——尽管标题如此,但它也可以与纯 C 一起使用。