为了int数组加入joinWithSeparator?

时间:2015-11-04 20:13:39

标签: arrays swift join

在新的Swift 2样式中,join必须由joinWithSeparator替换。但是我得到了错误消息,发现了模糊的引用:

var distribCharactersInt = [Int](count:lastIndex + 1, repeatedValue:0)
...                        
let DistributionCharacterString = distribCharactersInt.joinWithSeparator(",")

我忘了什么?

1 个答案:

答案 0 :(得分:6)

有两种joinWithSeparator()方法。一个需要一个 序列序列:

extension SequenceType where Generator.Element : SequenceType {
    /// Returns a view, whose elements are the result of interposing a given
    /// `separator` between the elements of the sequence `self`.
    ///
    /// For example,
    /// `[[1, 2, 3], [4, 5, 6], [7, 8, 9]].joinWithSeparator([-1, -2])`
    /// yields `[1, 2, 3, -1, -2, 4, 5, 6, -1, -2, 7, 8, 9]`.
    @warn_unused_result
    public func joinWithSeparator<Separator : SequenceType where Separator.Generator.Element == Generator.Element.Generator.Element>(separator: Separator) -> JoinSequence<Self>
}

,另一个采用一系列字符串(和一个字符串作为分隔符):

extension SequenceType where Generator.Element == String {
    /// Interpose the `separator` between elements of `self`, then concatenate
    /// the result.  For example:
    ///
    ///     ["foo", "bar", "baz"].joinWithSeparator("-|-") // "foo-|-bar-|-baz"
    @warn_unused_result
    public func joinWithSeparator(separator: String) -> String
}

你可能想要使用第二种方法,但是你有 将数字转换为字符串:

let distribCharactersInt = [Int](count:5, repeatedValue:0)
let distributionCharacterString = distribCharactersInt.map(String.init).joinWithSeparator(",")
print(distributionCharacterString) // 0,0,0,0,0