2

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

1
  • Error is in NetworkMonitor.pathUpdateHandler =, it is not allowed to use expressions in view builder blocks, only views. As well as views (Text in this case) inside callback does nothing, because they are views. Read about @State and how to update views. Commented Jul 20, 2020 at 17:08

1 Answer 1

6

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
            }
        }
    }


}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.