Reference Materials
Certification Courses
Created with over a decade of experience and thousands of feedback.
Python online compiler
JavaScript online compiler
SQL online compiler
Java online compiler
HTML online compiler
C online compiler
C++ online compiler
C# online compiler
PHP online compiler
Swift online compiler
Kotlin online compiler
TypeScript online compiler
Go online compiler
Rust online compiler
Scala online compiler
Dart online compiler
R online compiler
Ruby online compiler
Swift Set first
In this tutorial, we will learn about the Swift Set first property with the help of examples.
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
firstproperty 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
firstproperty.
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.
Did you find this article helpful?