Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose of Array "Join" function in Swift

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

like image 240
Kostiantyn Koval Avatar asked Jul 18 '14 13:07

Kostiantyn Koval


People also ask

What does the join method of an array do?

The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.

How do I merge two arrays in Swift?

Merge two arrays into a new array with Sequence 's joined() method and Array 's init(_:) initializer. Swift provides a joined() method for all types that conform to Sequence protocol (including Array ).


1 Answers

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

like image 161
zaph Avatar answered Sep 26 '22 21:09

zaph