Bruce A.
Bruce A.

Reputation: 33

Simplifying an If-Else If-Then statement in Swift

I'm building a soundboard, and I want to create a statement that says "If the pitchPlayer is playing, stop it and start a sound based on two other switch statuses, but if it isn't playing, then start the sound based on two other switch statuses. I know there's got to be a way to clean this up a bit so its not so convoluted, but I am a total beginner, so any help or reference material would be greatly appreciated.

@IBAction func Button1(_ sender: UIButton) {

    if pitchPlayer.isPlaying {
        pitchPlayer.stop()

        if sassSwitch.isOn {
            timePitch.pitch = -1500
            timePitch.rate = 0.5
            pitchPlayer.scheduleFile(LawaudioFile1, at: nil, completionHandler: nil)

            pitchPlayer.play()

        } else if chipSwitch.isOn {
            timePitch.pitch = +1500
            timePitch.rate = 2.0
            pitchPlayer.scheduleFile(LawaudioFile1, at: nil, completionHandler: nil)

            pitchPlayer.play()

        } else {
            timePitch.pitch = +0
            timePitch.rate = 1.0
            pitchPlayer.scheduleFile(LawaudioFile1, at: nil, completionHandler: nil)

            pitchPlayer.play()
        }

    } else {

        if sassSwitch.isOn {
            timePitch.pitch = -1500
            timePitch.rate = 0.5
            pitchPlayer.scheduleFile(LawaudioFile1, at: nil, completionHandler: nil)

            pitchPlayer.play()

        } else if chipSwitch.isOn {
            timePitch.pitch = +1500
            timePitch.rate = 2.0
            pitchPlayer.scheduleFile(LawaudioFile1, at: nil, completionHandler: nil)

            pitchPlayer.play()

        } else {
            timePitch.pitch = +0
            timePitch.rate = 1.0
            pitchPlayer.scheduleFile(LawaudioFile1, at: nil, completionHandler: nil)

            pitchPlayer.play()
        }

    }
}

Upvotes: 0

Views: 141

Answers (1)

Sahil Manchanda
Sahil Manchanda

Reputation: 10547

based on your current code

if pitchPlayer.isPlaying {
    pitchPlayer.stop()
}        
if sassSwitch.isOn {
    timePitch.pitch = -1500
    timePitch.rate = 0.5
} else if chipSwitch.isOn {
    timePitch.pitch = +1500
    timePitch.rate = 2.0
} else {
    timePitch.pitch = +0
    timePitch.rate = 1.0    
}
pitchPlayer.scheduleFile(LawaudioFile1, at: nil, completionHandler: nil)
pitchPlayer.play()

Upvotes: 4

Related Questions