Open In App

Swift Array joined() function

Last Updated : 02 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Swift support different type of generic collections and array is one of them. An array is an ordered collection of the same type of values like int, string, float, etc., you are not allowed to store the value of another type in an array(for example, in a string type of array we can only store string values, not integer value). It is a generic collection and can store duplicate values of the same type. If an array is assigned to a variable then that array is mutable means you are allowed to change the content and the size of the array. If an array is assigned to a constant then that array is immutable which means you are not allowed to change the content and size of the array. In Swift, we are allowed to join the elements of an array in a string using joined() function. This function creates a new string by concatenating all the elements of an array using a specified separator. We can also join all the elements of an array without any separator.

Syntax:

arrayName.joined(separator: delimiter)

Here, 

arrayName is the name of the array object. 

Parameter: This function can only take one parameter that a separator which is used to separate the elements in the string. It is an optional parameter.

Return Value: This function returns a new string which is formed by concatenating all the elements of the array. 

Example 1:

Swift




// Swift program to join all the elements of an array
import Swift
  
// Creating an array of string type
var gfg = ["Welcome", "to", "Geeks", "for", "Geeks", "Portal"]
  
// Joining all the elements of the array
// Using joined() function with separator
var finalres = gfg.joined(separator: " ")
  
// Displaying the final result
print("New String 1:", finalres)
  
print("----------------------")
  
// Joining all the elements of the array
// Using joined() function with separator
var finalres2 = gfg.joined(separator: "-")
  
// Displaying the final result
print("New String 2:", finalres2)


Output:

New String 1: Welcome to Geeks for Geeks Portal
----------------------
New String 2: Welcome-to-Geeks-for-Geeks-Portal

Example 2:

Swift




// Swift program to join all the elements of an array
import Swift
  
// Creating an array of string type
var gfg = ["Welcome", "to", "Geeks", "for", "Geeks", "Tutorials"]
  
// Joining all the elements of the array
// Using joined() function without any parameter
var finalres = gfg.joined()
  
// Displaying the final result
print("New String :", finalres)


Output:

New String : WelcometoGeeksforGeeksTutorials


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads