0

I'm new to Swift and find out that Swift has optional string. I have issue unwrapping this optional. Here's the exmple:

for row in try database.prepare("SELECT name FROM airline WHERE carrier_id = \"\(text2)\"") {
    print(row)
}

Results:

[Optional("Lion Air")]
[Optional("Malindo Air")]

I tried:

if let a = row {
    print(a)
}

but it shows the error:

'Statement.Element' (aka 'Array<Optional<Binding>>')

How can I unwrap that array string and just leave as string as usual?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
themasmul
  • 125
  • 1
  • 10
  • 1
    Read apple documentation. – Bista Apr 06 '18 at 03:52
  • Here are useful links to start: https://developer.apple.com/documentation/swift/optional https://stackoverflow.com/questions/24003642/what-is-an-optional-value-in-swift – Ahmad F Apr 06 '18 at 03:57

2 Answers2

0

try these and see:

// According to your current result
for arrayElement in row {
  print(arrayElement)

  if let arrayString = arrayElement.first {
    print(arrayString)
  }

}

Try this for proper solution:

for childArray in row {
   print("childArray - \(childArray)")
   for stringValue in childArray {
       print("stringValue - \(stringValue)")
   }
}

Here is tested solution

let row = [
 [Optional("Lion Air")],
 [Optional("Malindo Air")]
]


row.forEach { (childArray) in
    childArray.forEach({ (optinalString) in
        print("optinalString - \(String(describing: optinalString))")

        if let unoptionalString = optinalString {
            print("unoptionalString - \(unoptionalString)")
        }
    })
}

Result:

enter image description here

Krunal
  • 77,632
  • 48
  • 245
  • 261
  • @themasmul None of the are what you want since all of these only give you the first value. – rmaddy Apr 06 '18 at 03:57
  • @rmaddy - I agree with you, even I have a doubt, these are wrong. I need to correct – Krunal Apr 06 '18 at 03:57
  • @themasmul - try with an updated answer, previous one was providing only first element of array. But your variable `row` is an array of array. – Krunal Apr 06 '18 at 04:00
0

Try this, using flatMap

Here is example optional string array to string array using flatMap

let optarray = [Optional("Swift"),Optional("Java"),Optional("C"), nil]
let stringArray = optarray.flatMap{$0}
print(stringArray)

Output

["Swift", "Java", "C"]
iParesh
  • 2,338
  • 1
  • 18
  • 30