Skip to content

Instantly share code, notes, and snippets.

@evandcoleman
Created August 16, 2018 18:11
Show Gist options
  • Save evandcoleman/b6a2e644f130f6d35a3171b11f3d60f1 to your computer and use it in GitHub Desktop.
Save evandcoleman/b6a2e644f130f6d35a3171b11f3d60f1 to your computer and use it in GitHub Desktop.
import UIKit
struct AttributedString {
private let _attributedString = NSMutableAttributedString()
private let defaultAttributes: [NSAttributedStringKey: Any]
var attributedString: NSAttributedString {
return NSAttributedString(attributedString: _attributedString)
}
init(defaultAttributes: [NSAttributedStringKey: Any] = [:]) {
self.defaultAttributes = defaultAttributes
}
func append<T: StringProtocol>(_ string: T, attributes: [NSAttributedStringKey: Any]? = nil) -> AttributedString {
let mergedAttributes = attributes?
.merging(defaultAttributes, uniquingKeysWith: { l, _ in l })
_attributedString
.append(NSAttributedString(string: string.description, attributes: mergedAttributes ?? defaultAttributes))
return self
}
func append(attachment: NSTextAttachment) -> AttributedString {
_attributedString
.append(NSAttributedString(attachment: attachment))
return self
}
func appendNewline() -> AttributedString {
return append("\n")
}
func appendSpace() -> AttributedString {
return append(" ")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment