Last active
February 3, 2018 23:20
-
-
Save sketchytech/62f517f9cc1057918678 to your computer and use it in GitHub Desktop.
A paint pot analogy of functional programming in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
typealias PositionShape = CGRect -> CAShapeLayer | |
func rectangle(color:UIColor) -> PositionShape { | |
let shape = CAShapeLayer() | |
shape.fillColor = color.CGColor | |
return { | |
rect in | |
let path = CGPathCreateMutable() | |
CGPathAddRect(path, nil, rect) | |
shape.path = path | |
return shape | |
} | |
} | |
typealias ShapeRectangle = CGPoint -> CGRect | |
func startingPoint(point:CGPoint) -> ShapeRectangle { | |
return { | |
endPoint in | |
let startPointX = point.x < endPoint.x ? point.x : endPoint.x | |
let startPointY = point.y < endPoint.y ? point.y : endPoint.y | |
return CGRect(x: startPointX, y: startPointY, width: abs(endPoint.x-point.x), height: abs(endPoint.y-point.y)) | |
} | |
} | |
// the colour has been picked | |
let rectPainter = rectangle(UIColor.blueColor()) | |
// construct a CGRect from start and end points | |
let object = startingPoint(CGPoint(x: 150, y: 50)) | |
let objectRect = object(CGPoint(x: 50, y: 150)) | |
// create the CAShape layer | |
let rect = rectPainter(objectRect) | |
// add returned subview to a view | |
let view = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200)) | |
view.layer.addSublayer(rect) | |
view // see added view in playground |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment