Reputation: 45408
I'm trying to use joinWithSeparator to insert a separator element between the elements of an array. Based on the documentation, I should be able to do:
[1, 2, 3].joinWithSeparator([0])
to get:
[1, 0, 2, 0, 3]
Instead, I get:
repl.swift:3:11: error: type of expression is ambiguous without more context
[1, 2, 3].joinWithSeparator([0])
How can I do this?
Upvotes: 1
Views: 632
Reputation: 523214
joinWithSeparator
does not work like this. The input should be a sequence of sequence i.e.
// 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])
You could also intersperse by flatMap and then drop the last separator:
// swift 2 and 3:
[1, 2, 3].flatMap { [$0, 0] }.dropLast()
Upvotes: 4
Reputation: 130092
See the example in the generated Swift header:
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>
}
If you think about how it works on an array of String
, it's exactly the same.
Upvotes: 0