swift - 使用 fromCString 从 DS 读取时解包 Optional 值时意外发现 nil

标签 swift sqlite null unsafe-pointers

我正在从 dbtable 中读取数据,但在表的特定位置出现错误。我的 sql 没问题,因为我已经可以从同一张表中读取数据,但是在特定的行中出现错误,我想知道如何处理这个错误。我不是在寻找解决我的数据库问题的解决方案,我只是在寻找处理错误的方法,这样它就不会崩溃。

我有以下代码:

let unsafepointer=UnsafePointer<CChar>(sqlite3_column_text(statement, 2));
if unsafepointer != nil {
    sText=String.fromCString(unsafepointer)! // <<<<<< ERROR
} else {
   sText="unsafe text pointer is nil !";
}

我得到一个错误:

"fatal error: unexpectedly found nil while unwrapping an Optional value"

在标有 <<<<<< ERROR 的行.

不安全指针的值不是nil :

pointerValue : 2068355072

我该如何处理这个错误,以免我的应用程序崩溃?

最佳答案

另一种可能的解决方案是:

let unsafepointer=UnsafePointer<CChar>(sqlite3_column_text(statement, 2));
var sText = "unsafe text pointer is nil !";
if unsafepointer != nil{
    if let text = String.fromCString(unsafepointer) as String?{
        sText = text;
    }    
}

关于swift - 使用 fromCString 从 DS 读取时解包 Optional 值时意外发现 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37235624/

相关文章:

ios - Collection View 单元格刷新未发生

ios - 在 IOS 上的 Swift 3 应用程序中触摸一行时调用的 View Controller 方法的顺序是什么?

python - 使用 strftime 的 sqlite 查询始终返回 None

Delphi 对象、NIL 对象和接口(interface)

java - 为什么我的 Spring @Autowired 字段为空?

c - 带有 NULL addr 的 mmap 如何工作?

string - 为什么这个快速功能不起作用?

ios - 为什么我不能在 swift 3 的应用程序中使用后台模式?

c# - 如何使用嵌入资源的 DLL 加载?

python - 请求中的条件