Purpose of Array "Join" function in Swift

ArraysSwiftHigh Order-Component

Arrays Problem Overview


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 https://stackoverflow.com/questions/24820446/swift-array-join-exc-bad-access

Arrays Solutions


Solution 1 - Arrays

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKostiantyn KovalView Question on Stackoverflow
Solution 1 - ArrayszaphView Answer on Stackoverflow