Swift3,展开 Optional<Binding>(在 SQLite.swift 中)
Swift3, unwrapping Optional<Binding> (in SQLite.swift)
最优秀的SQLite.swift,我有
let stmt = try local.db!.prepare(..)
for row in stmt {
for tricky in row {
每个 "tricky" 是一个 Optional<Binding>
我知道解开每个棘手问题的唯一方法是这样
var printable:String = "
if let trickyNotNil = tricky {
if let anInt:Int64 = trickyNotNil as? Int64 {
print("it's an Int")
.. use anInt
}
if let aString:String = trickyNotNil as? String {
print("it's a String")
.. use aString}
}
else {
tricky is nil, do something else
}
在示例中,我很确定它只能是 Int64 或 String(或属于 String 的东西);我想人们可能不得不用默认情况来涵盖其中的任何其他可能性。
有没有更快捷的方法?
有没有办法获取Optional<Binding>
的类型?
(顺便说一句,具体来说,SQLite.swift;从 doco 到 "get the type of column n" 可能有一种我不知道的方法。那会很酷,但是,上一段中的问题仍然存在, 一般而言。)
您可以使用基于class的switch语句。这种 switch 语句的示例代码如下所示:
let array: [Any?] = ["One", 1, nil, "Two", 2]
for item in array {
switch item {
case let anInt as Int:
print("Element is int \(anInt)")
case let aString as String:
print("Element is String \"\(aString)\"")
case nil:
print("Element is nil")
default:
break
}
}
如果需要,您还可以在一个或多个案例中添加 where 子句:
let array: [Any?] = ["One", 1, nil, "Two", 2, "One Hundred", 100]
for item in array {
switch item {
case let anInt as Int
where anInt < 100:
print("Element is int < 100 == \(anInt)")
case let anInt as Int where anInt >= 100:
print("Element is int >= 100 == \(anInt)")
case let aString as String:
print("Element is String \"\(aString)\"")
case nil:
print("Element is nil")
default:
break
}
}
最优秀的SQLite.swift,我有
let stmt = try local.db!.prepare(..)
for row in stmt {
for tricky in row {
每个 "tricky" 是一个 Optional<Binding>
我知道解开每个棘手问题的唯一方法是这样
var printable:String = "
if let trickyNotNil = tricky {
if let anInt:Int64 = trickyNotNil as? Int64 {
print("it's an Int")
.. use anInt
}
if let aString:String = trickyNotNil as? String {
print("it's a String")
.. use aString}
}
else {
tricky is nil, do something else
}
在示例中,我很确定它只能是 Int64 或 String(或属于 String 的东西);我想人们可能不得不用默认情况来涵盖其中的任何其他可能性。
有没有更快捷的方法?
有没有办法获取Optional<Binding>
的类型?
(顺便说一句,具体来说,SQLite.swift;从 doco 到 "get the type of column n" 可能有一种我不知道的方法。那会很酷,但是,上一段中的问题仍然存在, 一般而言。)
您可以使用基于class的switch语句。这种 switch 语句的示例代码如下所示:
let array: [Any?] = ["One", 1, nil, "Two", 2]
for item in array {
switch item {
case let anInt as Int:
print("Element is int \(anInt)")
case let aString as String:
print("Element is String \"\(aString)\"")
case nil:
print("Element is nil")
default:
break
}
}
如果需要,您还可以在一个或多个案例中添加 where 子句:
let array: [Any?] = ["One", 1, nil, "Two", 2, "One Hundred", 100]
for item in array {
switch item {
case let anInt as Int
where anInt < 100:
print("Element is int < 100 == \(anInt)")
case let anInt as Int where anInt >= 100:
print("Element is int >= 100 == \(anInt)")
case let aString as String:
print("Element is String \"\(aString)\"")
case nil:
print("Element is nil")
default:
break
}
}