简体   繁体   中英

Swift error: "Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols" when calling function to write text

I'm trying to use a completion to write text, but I get the error "Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols" when I try to run it. Any help would be great, thank you!

VStack {
                    Image("external_white")
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .frame(width: 60, height: 60.0)
                    Text("External IP")
                    getExternalAddress("") { (test) -> Any in
                        Text(test)
                    }
                }

Called function:

func getExternalAddress(_ key: String, completion: @escaping (String) -> Any) {
    var test = key
    Ipify.getPublicIPAddress { result in
        switch result {
        case .success(let ip):
            print(ip + " ip") // "210.11.178.112"
            test = ip
            print(test + " test")
            completion(test)
        case .failure(let error):
            print(error.errorDescription)
        }
    }

You shouldn't try to do everything inside your view, SwiftUI introduces several ways to publish data between objects so instead use that.

In this examples I moved your function to another class that can be observed and that publishes the found IP address

class IpFinder: ObservableObject {
    @Published var ipAddress: String = ""

    func getExternalAddress(_ key: String) {
        var test = key
        Ipify.getPublicIPAddress { result in
            switch result {
            case .success(let ip):
                ipAddress = ip
            case .failure(let error):
                print(error.errorDescription)
            }
        }
    }
}

And then observe an instance of this class in your view

struct ContentView: View {
    @ObservedObject var ipFinder: IPFinder = IPFinder()
    @State var value = 0
    @State private var key = ""

    var body: some View {
        VStack {
            Image("external_white")
                .resizable()
                .aspectRatio(contentMode: .fit)
                .frame(width: 60, height: 60.0)
            Text("External IP")

            Text(ipFinder.ipAddress)

            TextField("key", text:$key)

            Button(action: {
                ipFinder.getExternalAddress(key)
            }, label: {
                Text("Get IP address")
            })
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM