【发布时间】:2017-05-07 11:27:20
【问题描述】:
有什么方法可以在 Swift 3 中实现以下功能?
let button = UIButton().apply {
$0.setImage(UIImage(named: "UserLocation"), for: .normal)
$0.addTarget(self, action: #selector(focusUserLocation),
for: .touchUpInside)
$0.translatesAutoresizingMaskIntoConstraints = false
$0.backgroundColor = UIColor.black.withAlphaComponent(0.5)
$0.layer.cornerRadius = 5
}
apply<T> 函数应该采用(T)->Void 类型的闭包,运行它并传递self,然后简单地返回self。
另一种选择是为此使用运算符,例如“=>”
(借鉴Kotlin 和Xtend 语言的想法)。
尝试像这样扩展NSObject:
extension NSObject {
func apply<T>(_ block: (T)->Void) -> T
{
block(self as! T)
return self as! T
}
}
但它需要在闭包中显式声明参数类型:
let button = UIButton().apply { (it: UIButton) in
it.setImage(UIImage(named: "UserLocation"), for: .normal)
it.addTarget(self, action: #selector(focusUserLocation),
for: .touchUpInside)
...
这不方便,并且使整个想法不值得付出努力。类型在对象创建时已经指定,应该可以不显式重复。
谢谢!
【问题讨论】:
-
我自己仍然对 Swift 中的泛型感到满意。但是,您无法对任何
NSObject执行您想要执行的操作。addTarget(_:for:)方法在 UIControl 中定义,setImage(_:for:)特定于UIButton。 -
你说得对,这正是我想将具体类型(可能作为泛型类型参数)放入 apply() 函数声明的原因。那么静态类型检查将不允许我调用错误的方法。
-
github.com/iwheelbuy/Decorator 如果它对你来说足够好 - 我可以发布答案
-
@AlexJenter 如果你有一个
UIButton()并且想用应用配置它,那么不需要任何样式。只需致电button.decorator.apply -
@iWheelBuy:我明白了。谢谢。
标签: ios swift functional-programming