Skip to content

Instantly share code, notes, and snippets.

@yoching
Last active September 7, 2017 07:34
Show Gist options
  • Save yoching/eb13ef4219d6a4ca8a76f2a4c82ee1f9 to your computer and use it in GitHub Desktop.
Save yoching/eb13ef4219d6a4ca8a76f2a4c82ee1f9 to your computer and use it in GitHub Desktop.
FuctionalViewStyleExperiments1
//: Playground - noun: a place where people can play
import UIKit
import XCPlayground
import PlaygroundSupport
let viewController = UIViewController()
viewController.view.backgroundColor = .white
let view = UIView()
view.backgroundColor = .orange
view.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
viewController.view.addSubview(view)
PlaygroundPage.current.liveView = viewController
typealias Style = (UIView) -> UIView // (UIView) -> Void でもいけそう(composeを変えれば)
func cornerRadius(_ radius: CGFloat) -> Style {
return { view in
view.layer.cornerRadius = radius
return view
}
}
/*
// un-curried version
func unCurriedCornerRadius(radius: CGFloat, view: UIView) {
view.layer.cornerRadius = radius
}
unCurriedCornerRadius(radius: 10, view: view)
*/
func borderWidth(_ width: CGFloat) -> Style {
return { view in
view.layer.borderWidth = width
return view
}
}
func borderColor(_ color: CGColor) -> Style {
return { view in
view.layer.borderColor = color
return view
}
}
// compose functions
// borderColor(UIColor.blue.cgColor)(borderWidth(10.0)(cornerRadius(radius: 10.0)(view)))
func compose(style style1: @escaping Style, with style2: @escaping Style) -> Style {
return { view in
return style2(style1(view))
}
}
func compose2(_ styles: Style...) -> Style {
return { view in
var composedView: UIView = view
for style in styles {
composedView = style(composedView)
}
return composedView
}
}
//let someBorder = compose(style: borderWidth(10.0), with: borderColor(UIColor.blue.cgColor))
//compose(
// style: someBorder,
// with: cornerRadius(10.0)
// )(view)
//compose2(borderWidth(10.0), borderColor(UIColor.blue.cgColor), cornerRadius(10.0))(view)
infix operator >>>
func >>>(style1: @escaping Style, style2: @escaping Style) -> Style {
return { view in
return style2(style1(view))
}
}
let finalStyle = (borderWidth(10.0) >>> borderColor(UIColor.blue.cgColor))
>>> cornerRadius(10.0)
finalStyle(view)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment