首页 > 解决方案 > 拆分字符串导致“任何?”类型的值 没有成员“组件”

问题描述

我有一个使用 swift 4 的 webview IOS 的功能。我正在尝试爆炸result,但我得到了Value of type 'Any?' has no member 'components',我不知道如何解决这个问题。我是新来的。

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    self.webView.evaluateJavaScript("document.getElementById('user_id').innerText") { (result, error) in
        if result != nil {
            let items = result.components(separatedBy: "|")
            self.ref?.child("people").child(result as! String).setValue(["device_token": self.deviceTokenStringfinal])
        }
    }
}

标签: swift

解决方案


因为result可以是任何东西:字符串、数字、数组、JSON 对象……取决于您的 Javascript 返回的内容。Swift 在编译时无法知道这一点,因此它标记resultAny.

您必须在运行时进行强制转换:

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    self.webView.evaluateJavaScript("document.getElementById('user_id').innerText") { (result, error) in
        guard let result = result as? String else { return }

        let items = result.components(separatedBy: "|")
        self.ref?.child("people").child(result).setValue(["device_token": self.deviceTokenStringfinal])
    }
}

推荐阅读