在Swift中简化If-Else If-Then语句

时间:2018-06-20 18:45:42

标签: swift if-statement

我正在构建一个音板,我想创建一个语句,说明“如果pitchPlayer正在播放,请停止播放并根据其他两个开关状态开始声音,但如果没有播放,然后根据其他两个开关状态启动声音,我知道必须有一种方法来解决这一问题,以免造成麻烦,但是我是个初学者,因此,非常感谢您提供帮助或参考资料。

@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()
        }

    }
}

1 个答案:

答案 0 :(得分:4)

根据您当前的代码

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()