Reputation: 31
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:
Type '()' cannot conform to '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:
Function declares an opaque return type, but has no return statements in its body from which to infer an underlying type
Thanks
Upvotes: 2
Views: 3395
Reputation: 515
Since you are calling a function, you can't do it inside your view construction, try called it inside 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
}
}
}
}
Upvotes: 6