{

How to Convert Array to Set in swift with example


Array and Set are both data structures used to store a collection of elements. Let’s see some differences between Array and store

Arrays:

  • Array stores the duplicate elements
  • It stores the elements in insertion order.

Set:

  • Set stores unique elements or objects
  • Order is not guaranteed
  • Set uses hashing values to store the objects, Hence retrieving the elements is faster compared to Array.

This tutorial explains multiple ways to Convert Array to Set in swift with example

How to convert Array to Set in Swift with examples

Set Constructor accepts array objects, It is easy to convert to Set. Here is an example

var array=["one", "two", "three"]
let set = Set(array)  
print(set)

Output:

["two", "three", "one"]

An example contains an array with duplicates, converted to Set and print unique values. Here is an example

var array=["one","one", "two", "three"]
let set = Set(array)  
print(set)

Output:

["two", "three", "one"]

Another using arrayLiteral in set Constructor

var set = Set<String>(arrayLiteral: "one", "two", "three") 
print(set) //["three", "two", "one"]
var set1 = Set<Int>(arrayLiteral: 1,4,5,6,1) 
print(set1) //[4, 1, 6, 5]

From the above examples, Type of the set is inferred based on the array of literal values.

If Array of the string returns data of typeSet<String> If Array of Int returns data of typeSet<Int>

How to convert Array of Struct to Set in Swift

Here, an Array of Custom objects that contain properties, is converted to a Set with object properties.

Following is an example

  • Created Struct of Employee that contains a name field
  • Next, Created an Array of Employees using literal syntax
  • Convert object array into Array of fields using the map method.
  • Pass Array of fields to Set constructor

Here is an example

struct Employee {
    let name: String
}

let employees = [
    Employee(name: "John"),
    Employee(name: "Mark"),
    Employee(name: "Lee"),
    Employee(name: "Frank"),
        Employee(name: "Frank")

]

let employeeNames = employees.map({ $0.name })
let set = Set(employeeNames)
print(set) //["Lee", "Mark", "John", "Frank"]

How to convert NSArray to Set in Swift with examples

NSArray is an Immutable class Objective class reference type.

Create an NSArray using an array literal constructor. Next, Create an Empty Set iterate NSArray using for in loop, and add to NSArray Here is an example

import Foundation
let array: NSArray = NSArray(array: [1,0,21,48,13,4,5])
var setData=Set<Int>();
for number in (array as? [Int])! {
    setData.insert(number)
}

print(setData)

Output:

[5, 21, 4, 1, 0, 48, 13]
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.