[英]Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols
I am currently learning swift, I was trying to make a simple app that shows whether or not you are connected to the internet but I keep getting the following error:我目前正在学习 swift,我正在尝试制作一个简单的应用程序来显示您是否已连接到互联网,但我不断收到以下错误:
Type '()' cannot conform to 'View';类型 '()' 不能符合 'View'; only struct/enum/class types can conform to protocols
只有结构/枚举/类类型可以符合协议
This is the code:这是代码:
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")
}
}
}
}
}
I had tried removing the VStack and the "Network Check" text but it sends another error on the var body: some View line:我曾尝试删除 VStack 和“网络检查”文本,但它在var 正文上发送另一个错误:一些视图行:
Function declares an opaque return type, but has no return statements in its body from which to infer an underlying type Function 声明了一个不透明的返回类型,但在其主体中没有返回语句来推断基础类型
Thanks谢谢
Since you are calling a function, you can't do it inside your view construction, try called it inside onAppear:由于您正在调用 function,因此您无法在视图构造中执行此操作,请尝试在 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
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.