类型 '()' 不能符合 'View';只有结构/枚举/类类型可以符合协议 [英] Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols

查看:177
本文介绍了类型 '()' 不能符合 'View';只有结构/枚举/类类型可以符合协议的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在快速学习,我试图制作一个简单的应用程序来显示您是否已连接到互联网,但我不断收到以下错误:

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:

类型'()'不能符合'View';只有 struct/enum/class 类型才能符合协议

Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols

这是代码:

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 和网络检查"text 但它在 var body: some View 行上发送另一个错误:

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

谢谢

推荐答案

既然你调用的是一个函数,你就不能在你的视图构造里面做,试试在 onAppear 里面调用它:

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


}

这篇关于类型 '()' 不能符合 'View';只有结构/枚举/类类型可以符合协议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆