gpt4 book ai didi

swift - 尝试以正确的方式处理错误和可选项

转载 作者:行者123 更新时间:2023-11-28 12:01:22 25 4
gpt4 key购买 nike

我正在尝试使用 SwiftSoup 来抓取一些 HTML。此示例基于 SwiftSoup github 文档,运行良好……

func scrape() throws {

do {
let htmlFromSomeSource = "<html><body><p class="nerp">HerpDerp</p><p class="narf">HoopDoop</p>"

let doc = try! SwiftSoup.parse(htmlFromSomeSource)
let tag = try! doc.select("p").first()!
let tagClass = try! tag.attr("class")
} catch {
print("oh dang")
throw Abort(.notFound)
}
print(tagClass)
}

…直到我弄乱了选择器或属性目标,此时由于隐式解包的可选值,一切都崩溃了(我认为这只是让聪明人开始的快速而肮脏的代码)。那个 do/catch 似乎根本没有帮助。

那么正确的方法是什么?这编译...

print("is there a doc?")
guard let doc = try? SwiftSoup.parse(response.body.description) else {
print("no doc")
throw Abort(.notFound)
}

print("should halt because there's no img")
guard let tag = try? doc.select("img").first()! else {
print("no paragraph tag")
throw Abort(.notFound)
}

print("should halt because there's no src")
guard let tagClass = try? tag.attr("src") else {
print("no src")
throw Abort(.notFound)
}

... 但如果我弄乱了选择器或属性,它又会崩溃,“在展开可选值时意外发现 nil”(在“有文档吗?”之后)。我以为守卫会在遇到 nil 时停止进程? (如果我将“try?”转换为“try”,编译器会提示“条件绑定(bind)的初始化程序必须具有可选类型”……)

最佳答案

如果您将函数声明为 throws,则函数内不需要 do - catch block 。只需删除 try 后的代码块和感叹号即可将错误传递给调用函数。

func scrape() throws { // add a return type
let htmlFromSomeSource = "<html><body><p class="nerp">HerpDerp</p><p class="narf">HoopDoop</p>"

let doc = try SwiftSoup.parse(htmlFromSomeSource)
guard let tag = try doc.select("p").first() else { throw Abort(.notFound) }
let tagClass = try tag.attr("class")
// return something
}

关于swift - 尝试以正确的方式处理错误和可选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50066295/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com