0

How to remove in print or data Optional() ? (swift3, xcode 8.2.1)

   let statement = try connection.prepare("SELECT * FROM persons") 
   for data in statement
   {
       print(data)

   }

// result print :

[Optional(1), Optional("John"), Optional("Do"), Optional("Pologne")]

thanks a lot every body

  • I don't have the time for a full answer, but let me link to a blog post by the generous Ole Begemann: it's all about "Optional(...)" in outputs: https://oleb.net/blog/2016/12/optionals-string-interpolation/. Oh, and know the type of your `data` variable. I guess it is `[Any?]`, but you should make sure about it, and understand what it means. – Gwendal Roué Feb 01 '17 at 16:00
  • Side note: sorry you had to leave GRDB.swift. GRDB is easier for people who write SQL like you. SQLite.swift makes it not very easy to process the results of raw SQL queries (as you can see). – Gwendal Roué Feb 01 '17 at 16:02
  • With GRDB, `print(row)`prints ``. Much easier to read. And to extract the first name, you write `let firstName: String = row.value("firstName")`. With SQLite.swift I don't even know how you get the first name (it is not [documented](https://github.com/stephencelis/SQLite.swift/blob/master/Documentation/Index.md#executing-arbitrary-sql), or more precisely the documentation makes it clear that it will be painful). – Gwendal Roué Feb 01 '17 at 16:06
  • thank you, I see you're worrying :) SQLite.swift is not very documented on some point. I will read your link and see what I understand. Otherwise, I would use GRDB.swift which is much more convenient indeed! –  Feb 01 '17 at 16:12

1 Answers1

0

If you want to traverse over the optional elements of an collection, you could make use of for case ... in loop, a variation of the for ... in loop. This allows you optionally bind each element passed as a non-optional to the scope of the loop, given that the element is not nil.

E.g.:

let statement: [Any?] = [1, "John", "Doe", "Pologne"]

for case let data? in statement { 
    print(data) 
} /*  1
      John
      Doe
      Pologne */
dfrib
  • 70,367
  • 12
  • 127
  • 192