![](/img/trans.png)
[英]Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols; calling functions with SwiftUI
[英]Swift error: "Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols" when calling function to write text
我正在嘗試使用完成來編寫文本,但是當我嘗試運行它時出現錯誤“類型‘()’不能符合‘視圖’;只有結構/枚舉/類類型可以符合協議”。 任何幫助都會很棒,謝謝!
VStack {
Image("external_white")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 60, height: 60.0)
Text("External IP")
getExternalAddress("") { (test) -> Any in
Text(test)
}
}
調用函數:
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)
}
}
你不應該試圖在你的視圖中做任何事情,SwiftUI 引入了幾種在對象之間發布數據的方法,所以請使用它。
在這個例子中,我將你的函數移到了另一個可以觀察的類,它發布了找到的 IP 地址
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)
}
}
}
}
然后在你的視圖中觀察這個類的一個實例
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")
})
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.