Skip to content

Instantly share code, notes, and snippets.

@KaQuMiQ
Created October 23, 2019 07:03
Show Gist options
  • Save KaQuMiQ/580c371ea9439a3c86aafc35b951df2f to your computer and use it in GitHub Desktop.
Save KaQuMiQ/580c371ea9439a3c86aafc35b951df2f to your computer and use it in GitHub Desktop.
Functional programming for functional scared
extension Style where T: UILabel {
public func font(_ weight: UIFont.Weight, size: CGFloat) -> Style<T> {
return with { label in
label.font = UIFont.systemFont(ofSize: size, weight: weight)
}
}
public func color(_ color: UIColor) -> Style<T> {
return with { label in
label.textColor = color
}
}
public func textAlignment(_ alignment: NSTextAlignment) -> Style<T> {
return with { label in
label.textAlignment = alignment
}
}
public func numberOfLines(_ numberOfLines: Int) -> Style<T> {
return with { label in
label.numberOfLines = numberOfLines
}
}
public func lineBreakMode(_ lineBreakMode: NSLineBreakMode) -> Style<T> {
return with { label in
label.lineBreakMode = lineBreakMode
}
}
}
public struct Style<T> {
private let style: (T) -> Void
private init(style: @escaping (T) -> Void) {
self.style = style
}
@discardableResult
public func apply(on subjects: T...) -> Style {
subjects.forEach { style($0) }
return self
}
public static func `for`(_: T.Type) -> Style {
return .init { _ in }
}
private func with(_ other: @escaping (T) -> Void) -> Style<T> {
return .init { subject in
self.apply(on: subject)
other(subject)
}
}
}
@KaQuMiQ
Copy link
Author

KaQuMiQ commented Oct 23, 2019

Usage example:

ler myLabelStyle = Style.for(UILabel.self).color(.red).numberOfLines(0)
let label1: UILabel = .init()
let label2: UILabel = .init()
myLabelStyle.apply(on: label1, label2)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment