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 foundationimport Foundation// create some stringslet str1 = "welcome to Edpresso"let str2 = "A-Good-Day"// print substrings separated by a separatorprint(str1.components(separatedBy: " "))print(str2.components(separatedBy: "-"))
Explanation
- Line 2: We import the
Foundationframework. It is a framework containing several APIs likeString,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 theString. - 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 theprint()function to the console.