如果将try语句放在for循环中,使用swift 5.1捕获的内容在哪里

问题描述 投票:0回答:1

我试图通过选择最后一行来查看是否已设置SQLite.swift数据库,如果未设置,我将从文件中重新加载数据库表。但是我使用的是基于SQLite.swift文档的代码,该文档在过于简短的示例代码中没有提供足够的上下文。

let query = Bible.select(id, Book, Chapter, Verse, KJV)
            .filter(id == 31102)

        for verse in try! db.prepare(query) {
            print("The Bible is in the DB.\n")
            DataLoaded = true
        } catch {
            DataLoaded = false
        }

我了解'!'尝试消除错误后,因此我最后提出的问题没有采取任何措施,但是如果我删除了“!”错误消息显示“此处的错误未得到处理”。如果我拿掉'!',我应该放在哪里?

swift
1个回答
0
投票

for循环无关紧要。 catch需要与do配对。

do {
    // anything involving a try
} catch {
}

所以您的代码应该更像这样:

do {
    for verse in try db.prepare(query) {
        print("The Bible is in the DB.\n")
    } 
    DataLoaded = true // Put this inside the loop if loading any data, and not all, is considered success
} catch {
    DataLoaded = false
}

并且不要将try!catch一起使用。只需使用try

© www.soinside.com 2019 - 2024. All rights reserved.