What is set.prefix() method in Swift?
Overview
The prefix() method is used on a set, and it returns a sub-sequence up to the specified length with the initial elements of the particular set.
Syntax
set.prefix(length)
Syntax for prefix() method of a Set in Swift
Parameters
The prefix() method takes length as a parameter that represents the number of elements of a sub-sequence, we want to return.
Return value
This method returns a sub-sequence.
Code example
Let's look at the code below:
// create some setslet names: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]let numbers: Set = [1, 2, 3, 4, 5, 7, 8, 9, 10]// get some sub-sequence using the prefix() methodvar prefix1 = names.prefix(2)var prefix2 = numbers.prefix(5)// print each elementfor each in prefix1{print(each)}// print each elementfor each in prefix2{print(each)}
Explanation
- Lines 2 and 3: We create a couple of sets.
- Lines 6 and 7: We get a particular sub-sequence of a set using the
prefix()method. Then, we store this sub-sequence in variablesprefix1andprefix2. - Line 10 to 15: We use the
for-inloop to print each element of the sub-sequences.