TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to SWIFT

Swift Join Strings: joined, separator Examples

Use the joined method to join a string array into a string. Use a delimiter comma.
Join. A string array contains many related strings. To combine these into a single string, we can use the joined() func. This is a simple and powerful func.
To join elements together, we use an instance method on the array. The argument is the delimiter string. An empty delimiter can be used.
First example. Here we join a 3-element string array on a comma char. The resulting string contains a comma in between the elements. No delimiter is at the start or the end.

Tip: Joined() can handle more than one character in the delimiter. But each delimiter is the same.

Swift program that uses join // A string array of three elements. let animals = ["cat", "dog", "bird"] // Join the elements together with a comma delimiter. let result = animals.joined(separator: ",") print(result) Output cat,dog,bird
Empty delimiter. Sometimes we want to just combine (concatenate) all the strings together. No delimiter is required. We specify an empty string literal as the delimiter.

Tip: This is much simpler than a loop and string concats. And on large collections it may have a performance advantage.

Swift program that uses empty delimiter // A string array. let values = ["A", "B", "C", "D"] // Join the elements with an empty delimiter. let result = values.joined() print(result) // Display length of the result. print(result.endIndex) Output ABCD Index(_base: Swift.String.UnicodeScalarView.Index(_position: 4), _countUTF16: 0)
A note. This is an important aspect of joined: it adds no trailing delimiter. So we do not need special logic to remove a final characters.
A review. Joined is the opposite of split. These two methods can round-trip data. With components(), we split apart strings (this is the opposite of joined).Split
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf