我正在使用一个 SQLite 库,其中查询返回可选值以及可能引发错误。我想有条件地解开该值,或者如果它返回错误则接收 nil 。我不完全确定如何措辞,这段代码将解释,这就是它的样子:
func getSomething() throws -> Value? {
//example function from library, returns optional or throws errors
}
func myFunctionToGetSpecificDate() -> Date? {
if let specificValue = db!.getSomething() {
let returnedValue = specificValue!
// it says I need to force unwrap specificValue,
// shouldn't it be unwrapped already?
let specificDate = Date.init(timeIntervalSinceReferenceDate: TimeInterval(returnedValue))
return time
} else {
return nil
}
}
有没有办法避免在那里强制展开?在更新到 Swift3 之前,我没有被迫在这里强制展开。
以下是实际代码。只是试图从所有条目中获取最新的时间戳:
func getLastDateWithData() -> Date? {
if let max = try? db!.scalar(eventTable.select(timestamp.max)){
let time = Date.init(timeIntervalSinceReferenceDate: TimeInterval(max!))
// will max ever be nil here? I don't want to force unwrap!
return time
} else {
return nil
}
}