nc14
nc14

Reputation: 559

Value of type _ cannot convert to specified type Set<> Swift

I'm trying to create a set of random exercises. I have made my struct Hashable and Equatable following the tutorial here https://medium.com/@JoyceMatos/hashable-protocols-in-swift-baf0cabeaebd and that is working fine so it's ready to be put in a Set<>.

When I use an Array to collect the workout exercises, as per below, it works fine. But when I switch to a Set<> I get an error "cannot convert value of type [_] to specified type 'Set'. What is it about 'Sets' that mean you can't map in the same way as an Array?

func generateWorkout() {
    let allPossibleExercises = masterExerciseArray
    let numberOfExercisesKey = Int(arc4random_uniform(4)+3)

//error triggers on the line below if I switch [WorkoutExercise]
//for Set<WorkoutExercise> (which conforms to Hashable/Equatable

let workoutSet : [WorkoutExercise] = (1...numberOfExercisesKey).map { _ in
        let randomKey = Int(arc4random_uniform(UInt32(allPossibleExercises.count)))

return WorkoutExerciseGenerator( name: allPossibleExercises[randomKey].name,
 maxReps: allPossibleExercises[randomKey].maxReps).generate()
    }
    print (workoutSet)
}

There is an answer here with a similar error message Cannot convert value of type '[_]' to specified type 'Array' but my array wouldn't be empty as in this example so I don't think this is the same root cause?

UPDATE : for anyone having the same problem, you can use Array but then simply convert the Array to a Set afterwards if the correct elements are Hashable/Equatable

Upvotes: 0

Views: 1726

Answers (1)

vadian
vadian

Reputation: 285290

If creating the array works create the array and then make the Set from the array. If all involved objects conform to Hashable this is supposed to work.

func generateWorkout() {
    let allPossibleExercises = masterExerciseArray
    let numberOfExercisesKey = Int(arc4random_uniform(4)+3)

    let workoutArray : [WorkoutExercise] = (1...numberOfExercisesKey).map { _ in
        let randomKey = Int(arc4random_uniform(UInt32(allPossibleExercises.count)))

        return WorkoutExerciseGenerator( name: allPossibleExercises[randomKey].name,
                                      maxReps: allPossibleExercises[randomKey].maxReps).generate()
    }
    let workoutSet = Set(workoutArray)
    print (workoutSet)
}

Upvotes: 2

Related Questions