是否有joinWithSeparator用于属性字符串

sha*_*sha 8 swift

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

let st = [ "apple", "pie", "potato" ]
st.joinWithSeparator(", ")
Run Code Online (Sandbox Code Playgroud)

结果我们将有"苹果,馅饼,土豆".

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

mix*_*xel 13

抓住:

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))
    }
}
Run Code Online (Sandbox Code Playgroud)


tol*_*ard 7

对于Swift 3.0,I切换到Array时不支持Sequence类型.我还更改方法名称以使用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))
    }
}
Run Code Online (Sandbox Code Playgroud)


Pie*_*sso 6

使用Sequence 更新了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))
    }
}
Run Code Online (Sandbox Code Playgroud)