The first
property returns the first element of the set.
Example
var languages: Set = ["Swift", "C", "Java"]
// check if leanguages is empty or not
var result = languages.first
print(result!)
// Output: Swift
first Syntax
The syntax of the set first
property is:
set.first
Here, set is an object of the Set
class.
first Return Values
The first
property returns the first element of set.
Notes:
- The
first
property returns an optional value, so we need to unwrap it. There are different techniques to unwrap optionals. To learn more about optionals, visit Swift Optionals. - Since sets are unordered, we will get different values from the
first
property.
Example: Swift set first
var names: Set = ["Gregory", "Perry", "Nadal"]
// return first element of names
print("First Name of set: ", names.first!)
var even: Set = [2, 4, 6, 8, 10]
// check first element of even
print("First Even Number:", even.first!)
Output
First Name of set: Perry First Even Number: 6
In the above example, the first element returns the first element of names and even respectively.
Since the sets are unordered, the first element can be any element of the sets. So the first property returns a random element from names and even.