Swift Array joined() function
Last Updated :
02 Jun, 2022
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
import Swift
var gfg = [ "Welcome" , "to" , "Geeks" , "for" , "Geeks" , "Portal" ]
var finalres = gfg.joined(separator: " " )
print ( "New String 1:" , finalres)
print ( "----------------------" )
var finalres2 = gfg.joined(separator: "-" )
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
import Swift
var gfg = [ "Welcome" , "to" , "Geeks" , "for" , "Geeks" , "Tutorials" ]
var finalres = gfg.joined()
print ( "New String :" , finalres)
|
Output:
New String : WelcometoGeeksforGeeksTutorials
Share your thoughts in the comments
Please Login to comment...