是否有joinWithSeparator用于属性字符串

时间:2015-09-28 19:38:31

标签: swift

可以使用joinWithSeparator方法将字符串数组与特定分隔符连接在一起。

let st = [ "apple", "pie", "potato" ]
st.joinWithSeparator(", ")

因此,我们将拥有"苹果,馅饼,土豆和#34;。

如果我在数组中归因于字符串怎么办?有没有简单的方法将它们组合成一个大的属性字符串?

3 个答案:

答案 0 :(得分:12)

捕捉:

import Foundation

extension SequenceType where Generator.Element: NSAttributedString {
    func joinWithSeparator(separator: NSAttributedString) -> NSAttributedString {
        var isFirst = true
        return self.reduce(NSMutableAttributedString()) {
            (r, e) in
            if isFirst {
                isFirst = false
            } else {
                r.appendAttributedString(separator)
            }
            r.appendAttributedString(e)
            return r
        }
    }

    func joinWithSeparator(separator: String) -> NSAttributedString {
        return joinWithSeparator(NSAttributedString(string: separator))
    }
}

答案 1 :(得分:5)

对于 Swift 3.0 ,我不支持序列类型切换到Array。我还更改方法名称以使用swift 3.0样式

extension Array where Element: NSAttributedString {
    func joined(separator: NSAttributedString) -> NSAttributedString {
        var isFirst = true
        return self.reduce(NSMutableAttributedString()) {
            (r, e) in
            if isFirst {
                isFirst = false
            } else {
                r.append(separator)
            }
            r.append(e)
            return r
        }
    }

    func joined(separator: String) -> NSAttributedString {
        return joined(separator: NSAttributedString(string: separator))
    }
}

答案 2 :(得分:4)

使用序列更新了 Swift 4 的答案以及一些基本文档:

extension Sequence where Iterator.Element: NSAttributedString {
    /// Returns a new attributed string by concatenating the elements of the sequence, adding the given separator between each element.
    /// - parameters:
    ///     - separator: A string to insert between each of the elements in this sequence. The default separator is an empty string.
    func joined(separator: NSAttributedString = NSAttributedString(string: "")) -> NSAttributedString {
        var isFirst = true
        return self.reduce(NSMutableAttributedString()) {
            (r, e) in
            if isFirst {
                isFirst = false
            } else {
                r.append(separator)
            }
            r.append(e)
            return r
        }
    }

    /// Returns a new attributed string by concatenating the elements of the sequence, adding the given separator between each element.
    /// - parameters:
    ///     - separator: A string to insert between each of the elements in this sequence. The default separator is an empty string.
    func joined(separator: String = "") -> NSAttributedString {
        return joined(separator: NSAttributedString(string: separator))
    }
}