错误:表达式<string?>不可转换为String

时间:2015-05-25 14:12:55

标签: swift sqlite.swift

我的代码是:

func getTimeStamps( tablename : String) -> String {
    let time_stamps = db["time_stamps"]
    let t_tabelle = Expression<String?>["tabelle"]
    let t_time_stamp = Expression<String?>["TIME_StAMP"]
    let query = time_stamps.filter(like(tablename, t_tabelle))

    return query[t_time_stamp]
}

但我在转换时遇到错误:

  

Expression<String?> is not convertible to String

如何返回字符串?

由于 Hauke

1 个答案:

答案 0 :(得分:0)

错误指的是getTimeStampsString -> String的函数签名的返回类型为String,但您返回的值为query[t_time_stamp]Expression<String?>

可以使用Query下标

Expression结构来返回表达式的命名空间版本:

let id = Expression<Int64>("id") // literally: "id"
let users = db["users"]
let users_id = users[id]         // literally: "users"."id"

在您的情况下,使用query下标t_time_stamp只会返回t_time_stamp表达式的新命名空间版本(在您的版本"time_stamps"."TIME_StAMP"中)。这对disambiguation很有帮助,但不太可能是您的意图。

很难从提供的代码确切告诉您要从函数返回的内容,但看起来您想要执行查询以提取值。一旦被提取,Row结构可以使用表达式进行下标以检索基础值。

如果您要查找单行,请尝试以下操作:

if let row = time_stamps.filter(like(tablename, t_tabelle)).first {
    return row[t_time_stamp]
}

但是,您的功能仍然会返回String,而不是String?。如果您的查询有可能返回零行或 返回的任何行返回到NULL时间戳列,则需要相应地处理您的选项。

但是,如果NULL时间戳表示编程错误/错误,则应相应地将String?更新为String

let t_time_stamp = Expression<String>["TIME_StAMP"]
// ...
return query.first![t_time_stamp]

请注意,如果您错误处理可选值的可能性,上述内容将会崩溃

相关问题