本文介绍了具有多个条件的for循环的过滤,关闭,功能语法版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to learn some ideas of functional programming, as they exist in Swift.

最近的问题中,通过(大师).

从这里:

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

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

Now I'm wondering how this technique can be applied to a problem where there's multiple criteria. Can this functional style be done to this:

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语句之后移至下一行

A guard statement is used to transfer program control out of a scope if one or more conditions aren’t met.in this example, if the condition is not met, ie there is no element in AVSpeechSynthesisVoice.speechVoices() that meet the criteria, guard let will transfer the program control out of the check function ,else if there is the some element in AVSpeechSynthesisVoice.speechVoices() that meet the criteria, program control goes to the next line after the guard let statement

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

}

check()

这篇关于具有多个条件的for循环的过滤,关闭,功能语法版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 00:27