我尝试使用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])我该怎么做呢?
发布于 2016-07-16 02:42:10
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()发布于 2016-07-16 02:45:48
参见生成的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数组上工作的,它是完全相同的。
https://stackoverflow.com/questions/38403051
复制相似问题