In Swift, the suffix()
method is used to return a subset of a set up to the given maximum length specified.
A set is a sequence of unique elements; its order is abnormal. This means that the first element we see in a set is not necessarily the first element. This is the way sets behave in Swift. With the suffix()
method, we can decide to return only the first two elements, the first five elements, and so on. This depends on the number specified.
set.suffix(length)
This method takes a parameter, length
, which represents the length or number of first n
elements that should be returned. For example, if we specify it as four, the first four elements are returned.
// create some setsvar names: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]var workers: Set = ["Alicia", "Bethany", "Diana"]var numbers: Set = [1, 2, 3, 4, 5, 7, 8, 9, 10]// create some sub sets or sub-sequenceslet subNumbers = numbers.suffix(2) // first two elementslet subNames = names.suffix(4) // first four elements// print elements returnedfor number in subNumbers{print(number)}for name in subNames{print(name)}
suffix()
method to get some subsets of the sets.for-in
loop, we print the elements of the sub-sets.