我是Swift的新手,发现Swift有可选的字符串。我有问题打开这个可选项。这是例子:
for row in try database.prepare("SELECT name FROM airline WHERE carrier_id = \"\(text2)\"") {
print(row)
}
结果:
[Optional("Lion Air")]
[Optional("Malindo Air")]
我试过了:
if let a = row {
print(a)
}
但它显示错误:
'Statement.Element'(又名'数组<可选< Binding>>')
如何解开该数组字符串并像往常一样保留字符串?
答案 0 :(得分:0)
试试这些,看看:
// According to your current result
for arrayElement in row {
print(arrayElement)
if let arrayString = arrayElement.first {
print(arrayString)
}
}
尝试这个以获得正确的解决方案:
for childArray in row {
print("childArray - \(childArray)")
for stringValue in childArray {
print("stringValue - \(stringValue)")
}
}
这是经过测试的解决方案
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)")
}
})
}
结果:
答案 1 :(得分:0)
使用flatMap
以下是使用flatMap
let optarray = [Optional("Swift"),Optional("Java"),Optional("C"), nil]
let stringArray = optarray.flatMap{$0}
print(stringArray)
<强>输出强>
["Swift", "Java", "C"]