Joe
Joe

Reputation: 23

How to avoid repeating functions

i have card game app that plays a sound file depending on the game scenario. Each scenario has an array of 6 sound files and 1 sound gets played randomly each time the function is called when the game scenario comes around.

There are 7 different scenarios with an array of sounds for each scenario. At the moment I have 7 different functions; 1 for each scenario. I am looking for a way to replace the 7 functions which are identical except for the sound array in each function with 1 function.

The function below is called when the player gets blackjack, another function will be called when the player gets bust, loses etc. These are the scenarios.

func soundArrayPlayerBlackjack(){

    let sounds = ["looks", "my seat2", "knicks", "daddy money", "cheeto", "whipped"]
         
         guard let sound = sounds.randomElement(),
             let soundURL = Bundle.main.url(forResource: sound, withExtension: "mp3") else { return }

         do {
             audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
         }
         catch {
             print(error)
         }

         audioPlayer?.play()}```

Upvotes: 0

Views: 99

Answers (1)

Sweeper
Sweeper

Reputation: 270790

You can instead write one function with a parameter called sounds:

func playRandomSound(sounds: [String]){
     guard let sound = sounds.randomElement(),
         let soundURL = Bundle.main.url(forResource: sound, withExtension: "mp3") else { return }

     do {
         audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
     }
     catch {
         print(error)
     }

     audioPlayer?.play()
}

Then, declare 7 arrays containing those sounds:

let blackJackSounds = ["looks", "my seat2", "knicks", "daddy money", "cheeto", "whipped"]
let getBustSounds = ["otherSound1", "otherSound2", "otherSound3"]
let loseSounds = ["foo", "bar", "baz"]
// and so on...

Instead of calling soundArrayPlayerBlackjack(), you should now call:

playRandomSound(sound: blackJackSounds)

For any other groups of sounds, just pass in the correct array.

Upvotes: 3

Related Questions