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

New Outcome with each print of an set

Forums > Swift

Hey, i wanted to print a set, the amount of times that there is items in the set. But the outcomes are the same, so: CBA,CBA,CBA or ACB,ACB,ACB but i want that every print is unique. Here is the sample code:

let chars = Set(["A", "B", "C"])
for char in chars {
    print(chars)
}

3      

3      

Sets do not have a defined order, but they are only ever reordered when you add or remove items. So when you create your Set here:

let chars = Set(["A", "B", "C"])

the order of the elements is, no pun intended, set (though not necessarily in the order the elements are defined) and will not change as you loop through it until/unless you add/remove items.

If you want to change the order of the items when they are printed each time through the loop, you should call shuffled() on your Set, like this:

let chars = Set(["A", "B", "C"])
for char in chars {
    print(chars.shuffled())
}

Note two things:

  1. This doesn't actually change the order the items are stored in the original Set because this just returns a new Array with the elements in a different order while leaving chars untouched.
  2. You don't actually need a Set here to achieve this; an Array would work just as well. If you need a Set for other reasons because of stuff going on elsewhere in your code, fine, but it's not necessary for this example.

3      

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.