Swift:NSMutableString 数组的 joined()?

问题描述 投票:0回答:1

在 Swift 中,您可以像这样加入一个

Array
of
String

let a = ["fee", "fi", "fo", "fum"]
print(a.joined(separator: " ")) // -> "fee fi fo fum"

这样的

Array
怎么加入
NSAttributedString

swift nsattributedstring
1个回答
0
投票

此扩展程序增加了加入

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))
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.