What is components(separatedBy:) method in Swift?

Overview

The components(separatedBy:) method is used to divide a string into substrings using the specified string separator.

Syntax

string.components(separated: separator)

Parameters

separator: The separator that will be used to separate the substrings of the string string. It can be a character or a string.

Return value

The value returned is an array of substrings of string separated by the specified separator.

Example

Let’s look at the code below:

// import foundation
import Foundation
// create some strings
let str1 = "welcome to Edpresso"
let str2 = "A-Good-Day"
// print substrings separated by a separator
print(str1.components(separatedBy: " "))
print(str2.components(separatedBy: "-"))

Explanation

  • Line 2: We import the Foundation framework. It is a framework containing several APIs like String, Date, and so on. It is useful when we want to use some of its functionalities. In this case, we want to use the functionality of the String.
  • Lines 5 and 6: We create two string values.
  • Lines 9 and 10: The components(separatedBy:) is used to convert the strings to an array of substrings separated by the given separators. The results are printed using the print() function to the console.