0

let arr = ["foo", "bar", nil, "baz"]

when I print it I get:

print(arr) // [Optional("foo"), Optional("bar"), nil, Optional("baz")]

However I'm looking to get an output that looks like:

print(arr) // ["foo", "bar", nil, "baz"]

I'm new to Swift's type system and the idea of downcasting and optionals. I know Optionals can be unwrapped using the ! operator or let x = arr.first {...} but I'm not sur how to get the result I'm looking for or if it's even possible.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Remove the `nil` value from your array. Presence of `nil` value in your array makes the array optional. – badhanganesh Jun 21 '17 at 20:28
  • Also related: [Swift: shortcut unwrapping of array of optionals](https://stackoverflow.com/q/25589605/2415822) – JAL Jun 21 '17 at 20:28
  • On the contrary, it is not a blatant dupe of any of them. None of them provides a way to do what this question asks: print the strings as strings (with quotes and without `Optional(...)`) while printing the nils as `nil` (without quotes). – rob mayoff Jun 21 '17 at 20:58
  • The answer, by the way, is `print(arr.map({ $0 ?? (nil as String? as Any) }))`. – rob mayoff Jun 21 '17 at 20:59
  • That's interesting. How does the `nil as String? as Any` type casting work? – William Gottschalk Jun 22 '17 at 22:01

0 Answers0