TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

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      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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.