You don't have to reduce an array to get it into a set; just create the set with an array: let objectSet = Set(objects.map { $0.URL }).

Answer from NRitH on Stack Overflow
🌐
TutorialsPoint
tutorialspoint.com › swift-program-to-convert-array-to-set
Swift Program to Convert Array to Set
February 8, 2023 - An array is used to store elements of the same data type in an order whereas a set is used to store distinct elements of the same data type without any definite order. To convert Array into set we use Set() initialiser. The resultant set contains the same elements as the original array but ...
🌐
SwiftLee
avanderlee.com › swiftlee › swift › array vs set: fundamentals in swift explained
Array vs Set: Fundamentals in Swift explained - SwiftLee
January 26, 2024 - A FREE 5-day email course revealing the 5 biggest mistakes iOS developers make with with async/await that lead to App Store rejections And migration projects taking months instead of days (even if you've been writing Swift for years) ... A big difference between Sets and Arrays is the uniqueness of elements.
Top answer
1 of 4
197

You don't have to reduce an array to get it into a set; just create the set with an array: let objectSet = Set(objects.map { $0.URL }).

2 of 4
42

With Swift 5.1, you can use one of the three following examples in order to solve your problem.


#1. Using Array's map(_:) method and Set's init(_:) initializer

In the simplest case, you can map you initial array to an array of urls (String) then create a set from that array. The Playground below code shows how to do it:

struct MyObject {
    let url: String
}

let objectArray = [
    MyObject(url: "mozilla.org"),
    MyObject(url: "gnu.org"),
    MyObject(url: "git-scm.com")
]

let urlArray = objectArray.map({ $0.url })
let urlSet = Set(urlArray)
dump(urlSet)
// ▿ 3 members
//   - "git-scm.com"
//   - "mozilla.org"
//   - "gnu.org"

#2. Using Array's reduce(into:_:) method

struct MyObject {
    let url: String
}

let objectArray = [
    MyObject(url: "mozilla.org"),
    MyObject(url: "gnu.org"),
    MyObject(url: "git-scm.com")
]

let urlSet = objectArray.reduce(into: Set<String>(), { (urls, object) in
    urls.insert(object.url)
})
dump(urlSet)
// ▿ 3 members
//   - "git-scm.com"
//   - "mozilla.org"
//   - "gnu.org"

As an alternative, you can use Array's reduce(_:_:) method:

struct MyObject {
    let url: String
}

let objectArray = [
    MyObject(url: "mozilla.org"),
    MyObject(url: "gnu.org"),
    MyObject(url: "git-scm.com")
]

let urlSet = objectArray.reduce(Set<String>(), { (partialSet, object) in
    var urls = partialSet
    urls.insert(object.url)
    return urls
})
dump(urlSet)
// ▿ 3 members
//   - "git-scm.com"
//   - "mozilla.org"
//   - "gnu.org"

#3. Using an Array extension

If necessary, you can create a mapToSet method for Array that takes a transform closure parameter and returns a Set. The Playground below code shows how to use it:

extension Array {

    func mapToSet<T: Hashable>(_ transform: (Element) -> T) -> Set<T> {
        var result = Set<T>()
        for item in self {
            result.insert(transform(item))
        }
        return result
    }

}

struct MyObject {
    let url: String
}

let objectArray = [
    MyObject(url: "mozilla.org"),
    MyObject(url: "gnu.org"),
    MyObject(url: "git-scm.com")
]

let urlSet = objectArray.mapToSet({ $0.url })
dump(urlSet)
// ▿ 3 members
//   - "git-scm.com"
//   - "mozilla.org"
//   - "gnu.org"
🌐
Hacking with Swift
hackingwithswift.com › example-code › language › when-to-use-a-set-rather-than-an-array
When to use a set rather than an array - free Swift example code and tips
November 28, 2019 - let array = [1, 2, 3] let set = Set(array) let array2 = Array(set) Using contains() on a set takes the same amount of time if you have one item as it does if you have one thousand items – it’s called an O(1) operation. NEW You don’t need more Swift tutorials. You need a plan, and that's where my book Everything but the Code comes in: it's designed to provide everything you need to go from Xcode to App Store – from coming up with killer ideas, to launch strategy, to breakout success.
🌐
Codecademy
codecademy.com › learn › learn-swift › modules › learn-swift-arrays › cheatsheet
Learn Swift: Arrays & Sets Cheatsheet | Codecademy
In Swift, a for-in loop can be used to iterate through the items of an array. This is a powerful tool for working with and manipulating a large amount of data. var employees = ["Michael", "Dwight", "Jim", "Pam", "Andy"] ... We can use a set ...
🌐
Swift.org
docs.swift.org › swift-book › documentation › the-swift-programming-language › collectiontypes
Documentation
This document is made available under a Creative Commons Attribution 4.0 International (CC BY 4.0) License · Swift and the Swift logo are trademarks of Apple Inc
🌐
Donny Wals
donnywals.com › how-to-decide-between-a-set-and-array-in-swift
How to decide between a Set and Array in Swift? – Donny Wals
October 2, 2024 - In this post, I’d like to explore two of the most common collection types; Set and Array. We’ll take a look at the key characteristics for each and we’ll explore use cases where we can use each. ... If we fully write out the type for myList, we’d write let myList: Array<String>. That’s because arrays in Swift can only contain a homogeneous collection of objects.
Find elsewhere
🌐
SerialCoder
serialcoder.dev › text-tutorials › swift-tutorials › arrays-vs-sets-in-swift
Arrays VS Sets In Swift – SerialCoder.dev
October 11, 2024 - From a practical point of view, there are two key differences that actually dictate whether we need to use the one or the other: Sets do not accept duplicate values, while arrays do.
🌐
Apple Developer
developer.apple.com › documentation › appstoreconnectapi › converting-arrays-to-sets
Converting arrays to sets | Apple Developer Documentation
Return the content of a list, with duplicates removed and sorted, so that you can compare it to another set.
🌐
GeeksforGeeks
geeksforgeeks.org › swift › swift-difference-between-sets-and-arrays
Swift - Difference Between Sets and Arrays - GeeksforGeeks
November 4, 2022 - For example, if we want to take 10 inputs from the user we can’t initialise 10 variables. In this case you can make use of arrays. It can store N number of elements into a single variable. Elements can be accessed by using indexing. ... // Swift program to illustrate array // Creating and initializing an Array with Integer Values var arr:[Int] = [ 1, 2, 3, 4, 5 ] // Display the array print(arr)
🌐
GeeksforGeeks
geeksforgeeks.org › swift › swift-set-operations
Swift - Set Operations - GeeksforGeeks
March 5, 2024 - A set can be created using the initializer or the set literal syntax. A set can also be created by adding an array of unique values to an empty set. We can use a set instead of an array when we want to remove duplicate values.
🌐
Medium
vikramios.medium.com › exploring-swift-collection-types-arrays-sets-and-dictionaries-3dda14348298
Exploring Swift Collection Types: Arrays, Sets, and Dictionaries
October 28, 2023 - Explore the power of collection types in Swift. From arrays to sets and dictionaries, uncover how these versatile data structures can streamline your code, manage data efficiently, and elevate your Swift programming skills
🌐
Hacking with Swift
hackingwithswift.com › quick-start › beginners › how-to-use-sets-for-fast-data-lookup
How to use sets for fast data lookup - a free Swift for Complete Beginners tutorial
November 8, 2021 - Creating a set works much like creating an array: tell Swift what kind of data it will store, then go ahead and add things. There are two important differences, though, and they are best demonstrated using some code. First, here’s how you would make a set of actor names: let people = Set(["Denzel Washington", "Tom Cruise", "Nicolas Cage", "Samuel L Jackson"])
🌐
SwiftyPlace
swiftyplace.com › home › swift arrays: from basics to advanced techniques
Swift Arrays: From Basics to Advanced Techniques - swiftyplace
October 11, 2023 - For instance, to declare an array of integers, you would write ... This declares an array of integers and initializes it with the numbers 1 through 5. Swift also supports type inference, which means you don’t have to explicitly specify the type of elements in the array if they can be inferred from the initial values.
Top answer
1 of 6
478

You can create an array with all elements from a given Swift Set simply with

let array = Array(someSet)

This works because Set conforms to the SequenceType protocol and an Array can be initialized with a sequence. Example:

let mySet = Set(["a", "b", "a"])  // Set<String>
let myArray = Array(mySet)        // Array<String>
print(myArray) // [b, a]
2 of 6
26

In the simplest case, with Swift 3, you can use Array's init(_:) initializer to get an Array from a Set. init(_:) has the following declaration:

init<S>(_ s: S) where S : Sequence, Element == S.Iterator.Element

Creates an array containing the elements of a sequence.

Usage:

let stringSet = Set(arrayLiteral: "car", "boat", "car", "bike", "toy")    
let stringArray = Array(stringSet)

print(stringArray)
// may print ["toy", "car", "bike", "boat"]

However, if you also want to perform some operations on each element of your Set while transforming it into an Array, you can use map, flatMap, sort, filter and other functional methods provided by Collection protocol:

let stringSet = Set(["car", "boat", "bike", "toy"])
let stringArray = stringSet.sorted()

print(stringArray)
// will print ["bike", "boat", "car", "toy"]
let stringSet = Set(arrayLiteral: "car", "boat", "car", "bike", "toy") 
let stringArray = stringSet.filter { $0.characters.first != "b" }

print(stringArray)
// may print ["car", "toy"]
let intSet = Set([1, 3, 5, 2]) 
let stringArray = intSet.flatMap { String($0) }

print(stringArray)
// may print ["5", "2", "3", "1"]
let intSet = Set([1, 3, 5, 2])
// alternative to `let intArray = Array(intSet)`
let intArray = intSet.map { $0 }

print(intArray)
// may print [5, 2, 3, 1]
🌐
Swift Forums
forums.swift.org › using swift
Assign elements at index, index+1, index+2 into array - Using Swift - Swift Forums
September 4, 2022 - Overview I have an array of numbers ... [numbers[1], numbers[2], numbers[3], ... ... [numbers[x], numbers[x+1], numbers[x+2], [numbers[x+1], [numbers[x+2], [numbers[x+2]] Example: If numbers = [23, 42, 19, 7, 150, 8, 20, 41] ...
🌐
Swift Forums
forums.swift.org › evolution › pitches
Provide map and flatMap for Set that return a Set - Pitches - Swift Forums
December 1, 2017 - Quite often I use map or flatMap on a Set and need a Set as result again. Both methods return an Array though. While it is quite easy to turn an Array back into a Set using its initializer init<S>(_ sequence: S) it is s…