Created
June 18, 2015 10:20
-
-
Save sketchytech/c02adc1b68fb1080ffc3 to your computer and use it in GitHub Desktop.
Functional Programming: Custom Operator 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 Attributer = NSAttributedString -> NSAttributedString | |
func underline(style:NSUnderlineStyle) -> Attributer { | |
return {aString in | |
let mString = aString.mutableCopy() | |
mString.addAttribute(NSUnderlineStyleAttributeName, value: style.rawValue, range: NSRange(location: 0, length: aString.length)) | |
return mString.copy() as! NSAttributedString | |
} | |
} | |
func color(color:UIColor) -> Attributer { | |
return {aString in | |
let mString = aString.mutableCopy() | |
mString.addAttribute(NSForegroundColorAttributeName, value: color, range: NSRange(location: 0, length: aString.length)) | |
return mString.copy() as! NSAttributedString | |
} | |
} | |
func highlight(color:UIColor) -> Attributer { | |
return {aString in | |
let mString = aString.mutableCopy() | |
mString.addAttribute(NSBackgroundColorAttributeName, value: color, range: NSRange(location: 0, length: aString.length)) | |
return mString.copy() as! NSAttributedString | |
} | |
} | |
infix operator >>> { associativity left } | |
func >>> (attributer1:Attributer,attributer2:Attributer) -> Attributer { | |
return {aString in attributer1(attributer2(aString))} | |
} | |
let combo = color(UIColor.blueColor()) | |
>>> highlight(UIColor.yellowColor()) | |
>>> underline(NSUnderlineStyle.StyleDouble) | |
let aString = NSAttributedString(string: "Hello Swift!") | |
combo(aString) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment