在 Swift 中,您可以像这样加入一个
Array
of String
:
let a = ["fee", "fi", "fo", "fum"]
print(a.joined(separator: " ")) // -> "fee fi fo fum"
这样的
Array
怎么加入NSAttributedString
?
此扩展程序增加了加入
Array
的 NSAttributedString
的能力,就像加入 String
s 一样。
extension Array where Element: NSAttributedString {
func joined(separator: NSAttributedString) -> NSAttributedString {
guard let firstElement = first else { return NSAttributedString() }
return dropFirst()
.reduce(into: NSMutableAttributedString(attributedString: firstElement)) { collector, element in
collector.append(separator)
collector.append(element)
}
}
func joined(separator: String = "") -> NSAttributedString {
joined(separator: NSAttributedString(string: separator))
}
}