具有多个条件的for循环的过滤,关闭,功能语法版本

困惑

我正在尝试学习一些函数式编程思想,就像Swift中存在的那样。

最近的问题,它表明如何更好地这可以通过Rickster(大师)。

由此:

var voiceToUse: AVSpeechSynthesisVoice?
let voices = AVSpeechSynthesisVoice.speechVoices()         
for voice in voices {
            if voice.name == "Arthur"
            {
                voiceToUse = voice
            }
        }

对此:

let voiceToUse = AVSpeechSynthesisVoice.speechVoices().filter({ $0.name == "Arthur" }).first

现在,我想知道如何将此技术应用于存在多个条件的问题。可以为此使用以下功能样式:

var voiceToUse: AVSpeechSynthesisVoice?
let voices = AVSpeechSynthesisVoice.speechVoices()     
for voice in voices {
                    if voice.name == "Samantha (Enhanced)"  && voice.quality == .enhanced
                    {
                        voiceToUse = voice
                    }
                }
萨米普·沙

如果要满足条件的数组的第一个元素,请使用此元素。

if let voiceToUse = AVSpeechSynthesisVoice.speechVoices().first(where: {
        $0.name == "Samantha (Enhanced)" && $0.quality == .enhanced
    }){

      //use the voiceTouse Variable

    }

如果要满足条件的数组元素的最后一个,请使用此元素。

if let voiceToUse = AVSpeechSynthesisVoice.speechVoices().reversed().first(where: {
       $0.name == "Samantha (Enhanced)" && $0.quality == .enhanced
    }){

      //use the voiceTouse Variable

    }

是的,我们可以使用警卫队...

如果不满足一个或多个条件,则使用保护声明将程序控制权移出作用域。在此示例中,如果不满足条件,即AVSpeechSynthesisVoice.speechVoices()中没有满足条件的元素,则卫兵将把程序控制从检查功能中移出,否则,如果AVSpeechSynthesisVoice中有某些元素。符合条件的SpeechVoices(),程序控制转到卫兵let语句后的下一行

func check(){
guard let voiceToUse =  AVSpeechSynthesisVoice.speechVoices().first(where: {
   $0.name == "Samantha (Enhanced)" && $0.quality == .enhanced
})else{
    return
}
 //use the voiceToUseVariable

}

check()

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章