60

What is the use of join() in arrays?

In other languages, it is used to join elements of array into string. For example,
Ruby Array.join

I've asked some question about join() in Swift Array join EXC_BAD_ACCESS

philipxy
  • 14,867
  • 6
  • 39
  • 83
Kostiantyn Koval
  • 8,407
  • 1
  • 45
  • 58

1 Answers1

160

Here is a somewhat useful example with strings:

Swift 3.0

let joiner = ":"
let elements = ["one", "two", "three"]
let joinedStrings = elements.joined(separator: joiner)
print("joinedStrings: \(joinedStrings)")

output:

joinedStrings: one:two:three

Swift 2.0

var joiner = ":"
var elements = ["one", "two", "three"]
var joinedStrings = elements.joinWithSeparator(joiner)
print("joinedStrings: \(joinedStrings)")

output:

joinedStrings: one:two:three

Swift 1.2:

var joiner = ":"
var elements = ["one", "two", "three"]
var joinedStrings = joiner.join(elements)
println("joinedStrings: \(joinedStrings)")

The same thing in Obj-C for comparison:

NSString *joiner = @":";
NSArray *elements = @[@"one", @"two", @"three"];
NSString *joinedStrings = [elements componentsJoinedByString:joiner];
NSLog(@"joinedStrings: %@", joinedStrings);

output:

joinedStrings: one:two:three

zaph
  • 111,848
  • 21
  • 189
  • 228
  • 1
    This isn't exactly answering the question. The OP asked for the join method on an array. You mentioned the join method on a string, which takes an array. The confusing part is that a normal array join methods take a string as an argument and join the array with the string, however, the array join method in string takes in an array, and joins each element of itself with the array given as an argument. – Perishable Dave Mar 12 '15 at 00:03
  • There is some context missing: This join function was changed after the initial release, the question/answer addresses that change of functionality. – zaph Mar 12 '15 at 01:24
  • 4
    As a sidenote: `joinWithSeparator` does work for Arrays with Strings, id est `[String]`, but not other Array types like `[Int]` – Binarian Oct 16 '15 at 08:39