为什么我不能将可选的Swift String传递给允许NULL指针的C函数? [英] Why can't I pass an optional Swift String to C function that allows NULL pointers?

查看:146
本文介绍了为什么我不能将可选的Swift String传递给允许NULL指针的C函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个处理C字符串的C函数.该函数实际上允许字符串为NULL指针.声明如下:

I have a C function that deals with C strings. The function actually allows strings to be NULL pointers. The declaration is like follows:

size_t embeddedSize ( const char *_Nullable string );

在C语言中使用此功能没问题:

It is no problem to use this function like this in C:

size_t s1 = embeddedSize("Test");
size_t s2 = embeddedSize(NULL); // s2 will be 0

现在我正在尝试从Swift中使用它.以下代码有效

Now I'm trying to use it from Swift. The following code works

let s1 = embeddedSize("Test")
let s2 = embeddedSize(nil) // s2 will be 0

但是什么都行不通呢?是给它传递一个可选的字符串!该代码将无法编译:

But what doesn't work is passing an optional string to it! This code will not compile:

let someString: String? = "Some String"
let s2 = embeddedSize(someString)

编译器抛出一个关于未解开可选选项的错误,Xcode询问我是否忘记添加!?.但是,为什么我要拆开它? NULLnil是要馈入函数的有效值.参见上文,我直接将nil传递给它,并且编译得很好,并返回了预期的结果.在我的真实代码中,字符串是从外部馈送的,它是可选的,我不能强行解开字符串,如果字符串为nil,则字符串将断开.那我怎么用一个可选的字符串来调用那个函数呢?

The compiler throws an error about the optional not being unwrapped and Xcode asks me if I maybe forgot to add ! or ?. However, why would I want to unwrap it? NULL or nil are valid values to be fed to the function. See above, I just passed nil to it directly and that compiled just well and returned the expected result. In my real code the string is fed from external and it is optional, I cannot force unwrap it, that will break if the string was nil. So how can I call that function with an optional string?

推荐答案

最可能的答案是,虽然字符串文字可转换为UnsafePointer<CChar>,而nil可转换为UnsafePointer<CChar>,而String也是,String?可能不在Swift 2中.

The most likely answer is that while string literals are convertible to UnsafePointer<CChar>, and nil is convertible to UnsafePointer<CChar>, and String also is, String? might not be in Swift 2.

这篇关于为什么我不能将可选的Swift String传递给允许NULL指针的C函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆