'JSContext'没有下标成员,oc可以,但是迅速无法使用
我尝试过快速4
OC可以,例如
JSContext *context = [[JSContext alloc] init];
context[@"makeNSColor"] = ^(NSDictionary *rgb)
{float r = rgb[@"red"].floatValue;
float g = rgb[@"green"].floatValue;
float b = rgb[@"blue"].floatValue;
return [NSColor colorWithRed:(r / 255.f) green:(g / 255.f) blue:(b / 255.f) alpha:1.0];
};
Swift is Error:
var context = JSContext() as? JSContext //Cannot assign value of type 'Any?' to type 'JSContext?'
context!["makeNSColor"] = { rgb in //Type 'JSContext' has no subscript member
var r: Float = rgb?["red"].floatValue
var g: Float = rgb?["green"].floatValue
var b: Float = rgb?["blue"].floatValue
return NSColor(red: CGFloat((r / 255.0)), green: CGFloat((g / 255.0)), blue: CGFloat((b / 255.0)), alpha: 1.0)
}
它有两个错误:无法分配'Any?'类型的值。键入“ JSContext?”,类型“ JSContext”没有下标成员,我不知道如何解决它,您能告诉我如何解决它,非常感谢。
我试图更改上下文!如! NSMutableDictionary或[String,Any],但仍然错误,无法更改
答案 0 :(得分:0)
将以下内容用于等效操作
let colorHandle: @convention(block) ([String : Any]) -> UIColor = { rgb in
let r = rgb["red"] as! CGFloat
let g = rgb["green"] as! CGFloat
let b = rgb["blue"] as! CGFloat
return UIColor(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: 1.0)
}
context?.setObject(colorHandle, forKeyedSubscript: "makeNSColor" as NSCopying & NSObjectProtocol)
答案 1 :(得分:0)
我不知道什么是对象makeNSColor
。但是,如果它是var makeNSColor = {red : 10/255, green : 10/255, blue : 255/255, a : 1};
,这是一个很好的示例,说明如何从字典makeNSColor
创建UIColor:
func f () {
let context = JSContext()!
let script = """
var makeNSColor = {red : 10/255, green : 10/255, blue : 255/255, a : 1};
"""
let cc = context.evaluateScript(script).context // result is
let val = cc?.objectForKeyedSubscript("makeNSColor")
guard let dict = val?.toDictionary() as? [String : CGFloat] else {return}
let color = UIColor(displayP3Red: dict["red"] ?? 0, green: dict["green"] ?? 0, blue: dict["blue"] ?? 0, alpha: dict["a"] ?? 0)
print(color)
}
如果要在JS中将makeNSColor
创建为Dictionary
,请使用下一个函数:
func addColor (r : Float, g : Float, b : Float) {
let context = JSContext()!
let script = """
var makeNSColor = {red : \(r)/255, green : \(g)/255, blue : \(b)/255, a : 1};
"""
let cc = context.evaluateScript(script).context // result is
// next code only needed to check the `makeNSColor`
let val = cc?.objectForKeyedSubscript("makeNSColor")
guard let dict = val?.toDictionary() as? [String : CGFloat] else {return}
let color = UIColor(displayP3Red: dict["red"] ?? 0, green: dict["green"] ?? 0, blue: dict["blue"] ?? 0, alpha: dict["a"] ?? 0)
print(color)
}