Skip to content

Commit 40af125

Browse files
committed
Add join() for attribute functions.
1 parent d5f64e0 commit 40af125

File tree

3 files changed

+55
-1
lines changed

3 files changed

+55
-1
lines changed

Attributed/AttributedStringConvertible.swift

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,11 @@
1010

1111
import Foundation
1212

13+
// MARK: - Function Types
14+
15+
/// An attribute function.
16+
public typealias AttributeFunction = [AttributedStringConvertible] -> AttributedStringConvertible
17+
1318
// MARK: - Protocol
1419

1520
/// A protocol for a type that can be converted to an attributed string.

Attributed/SequenceType+Join.swift

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,3 +18,17 @@ public extension SequenceType where Generator.Element == AttributedStringConvert
1818
return NestedAttributedString(attributes: [:], children: Array(self))
1919
}
2020
}
21+
22+
public extension SequenceType where Generator.Element == AttributeFunction
23+
{
24+
/// Joins a sequence of partially applied attribute functions (or, extension member functions of an attribute value)
25+
/// into a single function.
26+
///
27+
/// If redundant attributes are included, the later version will take precedence.
28+
public func join() -> AttributeFunction
29+
{
30+
return { strings in
31+
self.reverse().reduce(strings.join(), combine: { current, function in function([current]) })
32+
}
33+
}
34+
}

AttributedTests/AttributedTests.swift

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ class AttributedTests: XCTestCase
7777
XCTAssertEqual(attributed, mutable)
7878
}
7979

80-
func testJoin()
80+
func testStringJoin()
8181
{
8282
let attributed = [
8383
"Test",
@@ -89,4 +89,39 @@ class AttributedTests: XCTestCase
8989

9090
XCTAssertEqual(attributed, mutable)
9191
}
92+
93+
func testFunctionJoin()
94+
{
95+
let functions = [
96+
ColorType.blackColor().foregroundAttribute,
97+
ColorType.redColor().backgroundAttribute,
98+
2.kernAttribute
99+
]
100+
101+
XCTAssertEqual(
102+
functions.join()(["Test"]).attributedString,
103+
NSAttributedString(
104+
string: "Test",
105+
attributes: [
106+
NSForegroundColorAttributeName: ColorType.blackColor(),
107+
NSBackgroundColorAttributeName: ColorType.redColor(),
108+
NSKernAttributeName: 2
109+
]
110+
)
111+
)
112+
}
113+
114+
func testFunctionJoinOverride()
115+
{
116+
let functions = [
117+
ColorType.redColor().foregroundAttribute,
118+
ColorType.greenColor().foregroundAttribute,
119+
ColorType.blueColor().foregroundAttribute,
120+
]
121+
122+
XCTAssertEqual(
123+
functions.join()(["Test"]).attributedString,
124+
NSAttributedString(string: "Test", attributes: [NSForegroundColorAttributeName: ColorType.blueColor()])
125+
)
126+
}
92127
}

0 commit comments

Comments
 (0)