Created
July 28, 2014 18:24
-
-
Save tLewisII/0579ff3e30dbff880ee4 to your computer and use it in GitHub Desktop.
Attributed String builder for 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
// Playground - noun: a place where people can play | |
import Cocoa | |
enum StringAttribute { | |
case List([StringAttribute]) | |
case Font(NSFont) | |
case BgColor(NSColor) | |
case FgColor(NSColor) | |
func append(attr:StringAttribute) -> StringAttribute { | |
switch (self, attr) { | |
case let (.List(a), .List(b)): | |
var temp = a | |
temp.extend(b) | |
return .List(temp) | |
case let (.List(a), _): | |
return self.append(.List([attr])) | |
case let (_, .List(b)): | |
var temp = [self] | |
temp.extend(b) | |
return .List(temp) | |
default: | |
return .List([self, attr]) | |
} | |
} | |
private func key() -> NSString { | |
switch self { | |
case .Font(_): return NSFontAttributeName | |
case .BgColor(_): return NSBackgroundColorAttributeName | |
case .FgColor(_): return NSForegroundColorAttributeName | |
default: return "" | |
} | |
} | |
private func value() -> AnyObject { | |
switch self { | |
case let .Font(v): return v | |
case let .BgColor(v): return v | |
case let .FgColor(v): return v | |
default: return "" | |
} | |
} | |
private func makeAttribute() -> (String, AnyObject) { | |
switch self { | |
case let .Font(v): return (self.key(), v) | |
case let .BgColor(v): return (self.key(), v) | |
case let .FgColor(v): return (self.key(), v) | |
default: return ("", "") | |
} | |
} | |
private func makeAttributeDict() -> [String : AnyObject] { | |
var dict = [String : AnyObject]() | |
switch self { | |
case let .List(a): | |
for x in a { | |
let (key, val):(String, AnyObject) = x.makeAttribute() | |
dict[key] = val | |
} | |
case let .Font(f): dict.updateValue(f, forKey: self.key()) | |
case let .BgColor(c): dict.updateValue(c, forKey: self.key()) | |
case let .FgColor(c): dict.updateValue(c, forKey: self.key()) | |
} | |
return dict | |
} | |
func build(s:String) -> NSAttributedString { | |
let dict = self.makeAttributeDict() | |
return NSAttributedString(string: s, attributes: dict) | |
} | |
} | |
@infix func +(lhs:StringAttribute, rhs:StringAttribute) -> StringAttribute { | |
return lhs.append(rhs) | |
} | |
let attributes = .Font(NSFont(name: "Papyrus", size: 12)) + .BgColor(NSColor.redColor()) + .FgColor(NSColor.greenColor()) | |
attributes.build("this is a string") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment