swiftsqlite.swift

SwiftUI + Sqlite 3 (stephencelis) - how to create sqlite3 order statement in variable?


I use SQLite.swift library and have a question regarding the order method.

Related to the SQLite.swift sort syntax, I would like to put the sort order in a variable, as I need different sort statements for my query in reference to a special conditions in the code.

Here is the syntax when the sort is supplied as a parameter to order, as shown in the documentation:

users.order(email.asc, name.asc)

Here is my first try to move it into a variable:

let orderStatement: ??? = email.asc, name.asc // <– the correct assignment is my problem 
users.order(orderStatement)

What is the correct syntax to achieve my goal?


Solution

  • If you look at the Xcode “quick help” (--3), it tells you that order expects an Array of Expressible:

    func order(_ by: [any Expressible]) -> Table {…}
    

    Or there is also a variadic rendition:

    func order(_ by: any Expressible...) -> Table {…}
    

    quick help

    So, you can simply supply an array of any Expressible:

    let sortBy: [any Expressible] = [name.asc, email.asc]
    let query = users.order(sortBy)
    

    Or, you can infer the type:

    let sortBy = [name.asc, email.asc]
    let query = users.order(sortBy)