gpt4 book ai didi

ios - 如何在 Swift 中编写通用的 apply() 函数?

转载 作者:IT王子 更新时间:2023-10-29 05:25:10 27 4
gpt4 key购买 nike

有什么方法可以使以下内容在 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 .

另一种选择是为此使用运算符,例如“=>”(借用了 KotlinXtend 语言的想法)。

尝试扩展 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)
...

这很不方便,使整个想法不值得付出努力。类型已经在对象创建时指定,应该可以不明确重复。

谢谢!

最佳答案

HasApply 协议(protocol)

首先让我们定义HasApply协议(protocol)

protocol HasApply { }

及相关扩展

extension HasApply {
func apply(closure:(Self) -> ()) -> Self {
closure(self)
return self
}
}

接下来让 NSObject 符合 HasApply

extension NSObject: HasApply { }

就是这样

让我们测试一下

let button = UIButton().apply {
$0.titleLabel?.text = "Tap me"
}

print(button.titleLabel?.text) // Optional("Tap me")

注意事项

I wouldn't use NSObject (it's part of the Objective-C way of doing things and I assume it will be removed at some point in the future). I would prefer something like UIView instead.

extension UIView: HasApply { }

关于ios - 如何在 Swift 中编写通用的 apply() 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43830927/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com