[swift-evolution] Property Selectors

Robert Widmann devteam.codafi at gmail.com
Tue Mar 14 11:59:07 CDT 2017


Lenses <https://github.com/typelift/Focus>!  My only concern is that arbitrary effects can be attached to setters and getters, which can lead to surprising results when using the property reference.  As a language feature, I’d be interested to see where discussion around this will lead.

~Robert Widmann

> On Mar 14, 2017, at 4:02 AM, Andrew Thompson via swift-evolution <swift-evolution at swift.org> wrote:
> 
> Hello Swift Evolution Community,
> 
> I’ve been thinking about a new language feature that would allow properties to be first class citizens. The basic idea is as follows:
> 
> 	let x: PropertySelector<UIView, CGFloat> = #property(UIView.frame.origin.x)
> 	let view: UIView = …
> 	view.frame.origin.x = 20
> 	x.read(view) // returns 20
> 	x.write(view, value: 9091)
> 	view.frame.origin.x // now 9091
> 
> This is a trivial example, but now we can do more interesting things in our code. For example, we can animate any property on a view (that is documented to be animatable of course):
> 
> 	func animate(view: UIView, property: PropertySelector<UIView, CGFloat>, amount: Int) {
> 		let originalValue = property.read(view)
> 		func generateKeyFrames() {
> 			let step = 1.0 / Double(amount)
> 			for i in 0..<amount {
> 				let newValue = originalValue + CGFloat(i)
> 				let time = Double(i) / Double(amount)
> 				UIView.addKeyframe(withRelativeStartTime: time,
> 								  relativeDuration: step,
> 								  animations: { property.write(view, value: newValue) }
> 				)
> 			}
> 		}
> 		
> 		UIView.animateKeyframes(withDuration: 1.0,
> 							   delay: 0,
> 							   options: [],
> 							   animations: generateKeyFrames,
> 							   completion: nil)
> 	}
> 
> 	let myView: UIView = …
> 	myView.frame = CGRect(x: 20, y: 100, width: 99, height: 120)
> 
> 	// once this completes, myView.frame.origin.x == 120
> 	animate(view: myView, property: #property(UIView.frame.origin.x), amount: 100)
> 	
> 	// once this completes, myView.frame.size.width == 198
> 	animate(view: myView, property: #property(UIView.frame.size.width), amount: 99)
> 
> I think this would be a pretty neat feature to have, what do you think?
> 
> Cheers,
> - Andrew
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170314/a8c2695a/attachment.html>


More information about the swift-evolution mailing list