我尝试使用joinWithSeparator在数组元素之间插入分隔符元素。根据文档,我应该能够:
[1, 2, 3].joinWithSeparator([0])
得到:
[1, 0, 2, 0, 3]
相反,我得到:
repl.swift:3:11: error: type of expression is ambiguous without more context
[1, 2, 3].joinWithSeparator([0])
我该怎么做?
答案 0 :(得分:4)
joinWithSeparator
不能像这样工作。输入应该是一系列序列,即
// swift 2:
[[1], [2], [3]].joinWithSeparator([0])
// a lazy sequence that would give `[1, 0, 2, 0, 3]`.
// swift 3:
[[1], [2], [3]].joined(separator: [0])
您也可以通过flatMap散布,然后删除最后一个分隔符:
// swift 2 and 3:
[1, 2, 3].flatMap { [$0, 0] }.dropLast()
答案 1 :(得分:0)
请参阅生成的Swift标头中的示例:
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>
}
如果你想一下String
数组的工作方式,那就完全相同了。