Is there a way to get the next job in 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 }
The apply<T> function should take a closure of type (T)->Void , running the self run in it, and then just return self .
Another option would be to use the operator for this type of " => " (borrowed the idea from Kotlin and Xtend languages.)
Tried to do the NSObject extension as follows:
extension NSObject { func apply<T>(_ block: (T)->Void) -> T { block(self as! T) return self as! T } }
But this requires an explicit declaration of the parameter type in the closure:
let button = UIButton().apply { (it: UIButton) in it.setImage(UIImage(named: "UserLocation"), for: .normal) it.addTarget(self, action: #selector(focusUserLocation), for: .touchUpInside) ...
This is not convenient, and the whole idea is not worth the effort. The type is already specified when creating the object, and it should be possible not to repeat it explicitly.
Thanks!
source share