我目前正在学习快速,我正在尝试制作一个简单的应用程序,以显示您是否已连接到互联网,但我不断收到以下错误消息:
类型'()'不符合'视图';只有struct / enum / class类型可以符合协议
这是代码:
struct ContentView: View {
let NetworkMonitor = NWPathMonitor(requiredInterfaceType: .wifi)
var body: some View {
VStack { //Line with the error
Text("Network Check")
NetworkMonitor.pathUpdateHandler = {path in
if path.status == .satisfied {
Text("We are Connected")
} else {
Text("We are not connected")
}
}
}
}
}
我曾尝试删除VStack和“网络检查”文本,但它在 var主体上发送了另一个错误:一些View 行:
函数声明了一个不透明的返回类型,但是在其主体中没有返回语句可用来推断基础类型
谢谢
答案 0 :(得分:2)
由于您正在调用函数,因此无法在视图构造内完成操作,请尝试在onAppear内进行调用:
struct ContentView: View {
let NetworkMonitor = NWPathMonitor(requiredInterfaceType: .wifi)
@State var status = false
var body: some View {
VStack {
Text("Network Check")
if status {
Text("We are Connected")
} else {
Text("We are not connected")
}
}.onAppear() {
NetworkMonitor.pathUpdateHandler = { path in
self.status = path.status == .satisfied
}
}
}
}