我真的是編碼新手,我正在嘗試 swiftSoup,但是當我輸入代碼時,它給了我這個錯誤:(包含控制流陳述句的閉包不能與結果構建器“ViewBuilder”一起使用)如果我輸入代碼在錯誤的地方或者我忘記了一些東西!
在此處輸入圖片說明
這是代碼
import SwiftUI
import SwiftSoup
struct ContentView: View {
var body: some View {
do {
let html = "<html><head><title>First parse</title></head>"
"<body><p>Parsed HTML into a doc.</p></body></html>"
let doc: Document = try SwiftSoup.parse(html)
let p: Element = try doc.select("title").first()!
rint(p)
} catch Exception.Error(let type, let message) {
print(message)
} catch {
print("error")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
uj5u.com熱心網友回復:
不幸的是,您的代碼有點混亂。
你在哪里看到這個:
struct ContentView: View {
var body: some View {
// Some Stuff here
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
這是試圖為您的應用程式創建用戶界面的 SwiftUI 代碼。不幸的是,它不像“正常”的 Swift 代碼。有一些幕后作業使創建用戶界面變得容易,但如果您不熟悉編程,則很難理解。
你把你的“普通舊代碼”放在視圖宣告的中間,編譯器在那里看到它很困惑。
相反,讓我們將您的代碼放入一個函式中。然后就可以呼叫函式了。
struct ContentView: View {
var body: some View {
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
func parseSomeHTML() {
do {
let html = """
<html>
<head>
<title>First parse</title>
</head>"
<body>
<p>Parsed HTML into a doc.</p>
</body>
</html>
"""
let doc: Document = try SwiftSoup.parse(html)
let p: Element = try doc.select("title").first()!
print(p)
} catch Exception.Error(let type, let message) {
print(message)
} catch {
print("error")
}
}
現在你的代碼存在于一個普通的 Swift 函式中。但是你需要從某個地方呼叫它。讓我們添加一個按鈕來呼叫您的函式。將 contentView 更改為:
struct ContentView: View {
var body: some View {
Button("Push Me", action: { parseSomeHTML() })
}
}
Now when you run your app, you should have a button, and pushing that button should call the parseSomeHTML function.
(Note how I used triple double quotes (""") to format a multi-line string with your HTML. It's not necessary, what you had should work, but it's prettier)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/354807.html
