It was pointed out in the comments under the question, but I'd like to clearly state that there is a method for that very same purpose:

mutating func formUnion<S>(_ other: S) where Element == S.Element, S : Sequence

Usage:

var attendees: Set = ["Alicia", "Bethany", "Diana"]
let visitors = ["Diana", "Marcia", "Nathaniel"]
attendees.formUnion(visitors)
print(attendees)
// Prints "["Diana", "Nathaniel", "Bethany", "Alicia", "Marcia"]"

Source: Apple Developer


There is also an immutable variant which returns a new instance containing the union:

func union<S>(_ other: S) -> Set<Set.Element> where Element == S.Element, S : Sequence

Usage:

let attendees: Set = ["Alicia", "Bethany", "Diana"]
let visitors = ["Marcia", "Nathaniel"]
let attendeesAndVisitors = attendees.union(visitors)
print(attendeesAndVisitors)
// Prints "["Diana", "Nathaniel", "Bethany", "Alicia", "Marcia"]"

Source: Apple Developer

Answer from Arkadii on Stack Overflow
🌐
Codecademy
codecademy.com › learn › learn-swift › modules › learn-swift-arrays › cheatsheet
Learn Swift: Arrays & Sets Cheatsheet | Codecademy
The values of the set must be contained within brackets [] and separated with commas ,. ... To insert a single value into a set, append .insert() to a set and place the new value inside the parentheses ().
🌐
TutorialsPoint
tutorialspoint.com › swift-program-to-add-elements-to-a-set
Swift Program to Add Elements to a Set
Swift provide inbuilt functions named as formUnion() and insert() function to insert elements to a set. Lets discuss both the methods in detail along with examples. The formUnion(_:) function is used to insert elements of the given collection into the set. func formUnion(newSequence) Where ...
🌐
Programiz
programiz.com › swift-programming › library › set › insert
Swift Set insert() (With Examples)
// add "C++" to the languages set languages.insert("C++") print(languages) var priceList: Set = [12, 21, 35]
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"
🌐
Programiz
programiz.com › swift-programming › sets
Swift Sets (With Examples)
Since all the elements of the set are integers, studentID is a set of Int type. ... Note: When you run this code, you might get output in a different order. This is because the set has no particular order. We use the insert() method to add the specified element to a set.
🌐
Dot Net Perls
dotnetperls.com › set-swift
Swift - Set Examples: Insert and Contains - Dot Net Perls
var languages = Set<String>() languages.insert("Swift") languages.insert("Python") languages.insert("Ruby") // Loop over all elements in the set. // ... Ordering is not maintained.
Find elsewhere
🌐
Programiz
programiz.com › swift-programming › library › array › insert
Swift Array insert() (with Examples)
Swift Array suffix() Swift String insert() Swift Set insert() Swift Set formUnion() Swift Array remove() Swift Set update() Swift Arrays · The insert() method inserts an element to the array at the specified index.
🌐
Codecademy
codecademy.com › docs › swift › arrays › .insert()
Swift | Arrays | .insert() | Codecademy
October 11, 2022 - The .insert() method will add an element to a desired position of an array. When an element is added at the specified index, all later ones are pushed to the right in order to make room.
🌐
SerialCoder
serialcoder.dev › text-tutorials › swift-tutorials › arrays-vs-sets-in-swift
Arrays VS Sets In Swift – SerialCoder.dev
Arrays and sets use different methods for adding new elements in the collection. In arrays there is the append(_:) method: The above adds the new value as the last element to the array. We can also insert a value to a specific index using the insert(_:at:) method:
🌐
TutorialKart
tutorialkart.com › swift-tutorial › insert-element-to-set-swift
How to Add or Insert an element to Set in Swift?
May 9, 2021 - To insert an element to a Set, use insert() method. The syntax is: setName.insert(element). Example Swift programs are provided to explain in detail.
🌐
SwiftLee
avanderlee.com › swiftlee › swift › array vs set: fundamentals in swift explained
Array vs Set: Fundamentals in Swift explained - SwiftLee
January 26, 2024 - An Array can contain the same value twice while a Set will never contain duplicates. This is also the reason that the above insert(_:) method is returning a boolean to indicate whether the insert actually succeeded.
🌐
Educative
educative.io › answers › how-to-insert-elements-anywhere-in-an-array-in-swift
How to insert elements anywhere in an array in Swift
All we need to do is specify the elements we want to insert, along with the index position of where the insertion should begin. ... The value returned is a new array with the specified elements inserted at the index position index.
🌐
Cocoa Casts
cocoacasts.com › swift-fundamentals-arrays-and-sets
Cocoacasts
While each collection type has a unique set of features, the collection types of Swift's standard library also have a few things in common. The values and keys stored by arrays, sets, and dictionaries are strictly typed. In other words, you cannot insert an integer into an array of strings.
🌐
Donny Wals
donnywals.com › how-to-add-an-element-to-the-start-of-an-array-in-swift
How to add an element to the start of an Array in Swift?
April 23, 2024 - Swift fundamentals · You can use Array's insert(_:at:) method to insert a new element at the start, or any other arbitrary position of an Array: var array = ["world"] array.insert("hello", at: 0) // array is now ["hello", "world"] Make sure ...