0

My code is:

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]
}

But I get an error on conversion:

Expression<String?> is not convertible to String

How can I return a String?

Thanks Hauke

matt
  • 515,959
  • 87
  • 875
  • 1,141

1 Answers1

0

The error refers to the fact that your function signature for getTimeStamps, String -> String, has return type String, but the value you're returning, query[t_time_stamp], is an Expression<String?>.

Query structures can be subscripted with Expressions to return a namespaced version of the expression:

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

In your case, subscripting query with t_time_stamp is merely returning a new, namespaced version of the t_time_stamp expression (in your version, "time_stamps"."TIME_StAMP"). This is helpful for disambiguation, but unlikely your intent.

It's tough to tell from the code provided exactly what you want to return from the function, but it looks like you want to execute the query in order to extract a value. Row structures, once fetched, can be subscripted with expressions to retrieve the underlying value.

If you're looking to retrieve a single row, try the following:

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

Your function, however, still returns String, not String?. If it's ever possible for your query to return zero rows or for any of the rows it does return to have a NULL timestamp column, you need to handle your optionals accordingly.

If, however, a NULL timestamp would indicate a programming error/bug, you should update String? to String accordingly:

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

Please note that the above will crash if you're mishandling the potential for optional values.

stephencelis
  • 4,954
  • 2
  • 29
  • 22