实际上,我希望有一个返回元类型的协议(例如:Type.Type),我可以传递给一个Class,然后当我需要时,将一个对象转换为该MetaType.我要强制转换它的原因是它将在tableView dequeue函数中使用,我想要转换为我指定的Type I.
考虑这个精简版(下面的完整版).
let anyObject: AnyObject = anything()
let aType = type.type() // aType here is A.Type
if let newType = anyObject as? aType {
print(newType)
}
// error: 'aType' is not a type
Run Code Online (Sandbox Code Playgroud)
我很困惑为什么这不是一个类型,因为我们可以去aType.init()来初始化它?
下面是完整的示例代码(可以在Playground中运行).
import UIKit
protocol P {
func type() -> A.Type
}
class A {
}
class B: A {
}
class C: A {
}
struct BData: P {
func type() -> A.Type {
return B.self
}
}
struct Foo {
let type: P …Run Code Online (Sandbox Code Playgroud) 我们有一个示例HTML页面,它只链接.js文件:
sample.html:
<html>
<head>
<script src="test.js"></script>
</head>
<body></body>
</html>
Run Code Online (Sandbox Code Playgroud)
.js文件实际上只是:
test.js
function myFunction() {
return "hello";
}
Run Code Online (Sandbox Code Playgroud)
所以我想要的是评估Javascript函数(现在).在Swift文件中:
let webView = WKWebView(frame: .zero, configuration: WKWebViewConfiguration())
let path = Bundle.main.url(forResource: "sample", withExtension: "html")!
let text = try! String(contentsOf: path, encoding: String.Encoding.utf8)
webView.loadHTMLString(text, baseURL: nil)
webView.evaluateJavaScript("myFunction()") { (any, error) in
dump(error)
}
Run Code Online (Sandbox Code Playgroud)
我们得到错误的两个:
Error Domain = WKErrorDomain Code = 4"发生JavaScript异常"UserInfo = {WKJavaScriptExceptionLineNumber = 1,WKJavaScriptExceptionMessage = ReferenceError:找不到变量:myFunction,WKJavaScriptExceptionSourceURL = about:blank,NSLocalizedDescription =发生JavaScript异常,WKJavaScriptExceptionColumnNumber = 11}
我接近这个完全错了吗?