UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: How to filter array according to set content?

Forums > Swift

Looks basic, but I can't figure it out.

var array = [1, 2, 3, 4, 5, 6, 7]
var filteredArray: [Int] = []

var set = Set<Int>()
set.insert(1)
set.insert(2)
set.insert(3)
set.insert(4)

for s in set {
    filteredArray = array.filter { $0 == s }
}

print(filteredArray)

Expected outcome:

[1, 2, 3, 4]

Actual outcome:

// Single random number [4]

2      

First of all, a Set is defined as an unordered collection of unique elements, which means there is no specified sequence order. If you wish to apply a sort order then you have to do that yourself, external to the Set.

var array = [1, 2, 3, 4, 5, 6, 7]
var filteredArray: [Int] = []

// var set = Set<Int>()
// set.insert(1)
// set.insert(2)
// set.insert(3)
// set.insert(4)

let set: Set = [4, 1, 3, 2]   // order does not matter as Set is an unordered collection of elements

for s in set {
    filteredArray.append(contentsOf: array.filter { $0 == s } )
}

print(filteredArray)  // will print effectively in a random order, as Set is unordered.
print(filteredArray.sorted())

2      

@Greenamberred, thanks! Got the logic now!

2      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.