Skip to content

Instantly share code, notes, and snippets.

@sketchytech
Last active February 3, 2018 23:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sketchytech/62f517f9cc1057918678 to your computer and use it in GitHub Desktop.
Save sketchytech/62f517f9cc1057918678 to your computer and use it in GitHub Desktop.
A paint pot analogy of functional programming in Swift
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