我想创建一个UnsafeMutablePointer
对象来指向/表示一个现有的UIColor
对象。提供的初始化程序不提供此选项AFAIK。我能做什么?我想做这样的事情:
var myColor = UIColor.white
var pointer = UnsafeMutablePointer<UIColor>.init(from: myColor)
let color = pointer.pointee
// color == UIColor.white
pointer.pointee = UIColor.orange
// now myColor == UIColor.orange
我正在使用Swift 4.2
编辑:应评论者的要求,我正在发布真实代码:
let variableForColor : (_ key: String, _ color: UnsafeMutablePointer<UIColor>) -> StorableVariable.ValueForUIColor = { key, color in
return StorableVariable.ValueForUIColor.from(color: color.pointee, listener: { [weak self] v in
color.pointee = v.toUIColor()
self?.editor?.restyle()
})
}
...
let v = variableForColor("/button/circle/normal/fill/color", &editor!.styleOrangeButtonCircleNormalFillColor) // styleOrangeButtonCircleNormalFillColor is UIColor var in editor
编辑:以下是尝试使用inout
和Float
的解决方案,但编译器不允许这样做:
let variableForFloatIO : (_ key: String, _ float:inout Float) -> StorableVariable.ValueForFloat = { key, float in
return StorableVariable.ValueForFloat.init(value: float, default: float, min: 0, max: 1, step: 0.01, listener: { [weak self] v in
float = v // Error: Escaping closures can only capture inout parameters explicitly by value
self?.editor?.restyle()
})
}