gpt4 book ai didi

swift - 过滤器、闭包、具有多个条件的 for 循环的函数式语法版本

转载 作者:可可西里 更新时间:2023-11-01 00:02:49 24 4
gpt4 key购买 nike

我正在尝试学习函数式编程的一些思想,因为它们存在于 Swift 中。

recent question 中,显示了这能有多好,作者 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
}
}

最佳答案

您的单一条件表达式在闭包语法中使用了两个快捷方式:

1 - 如果只有一个表达式,则隐式返回它的值

2 - $0 引用第一个参数 - 编译器推断它的类型

因此,您可以将表达式扩展为多个子句,只要它仍然是单个表达式即可:

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

没有这两个快捷方式的等价物是这样的:

let voiceToUseB = AVSpeechSynthesisVoice.speechVoices().filter(
{ voice in
let found:Bool = voice.name == "Samantha (Enhanced)" && voice.quality == .enhanced
return found
}).first

关于swift - 过滤器、闭包、具有多个条件的 for 循环的函数式语法版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40665160/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com