swift 参数类型 () -> ()

swift argument type () -> ()

func speak(text:String, onComplete:()->()) {

    mySpeechUtterance = AVSpeechUtterance(string: text)
    mySpeechSynthesizer.speakUtterance(mySpeechUtterance)

    onComplete()
}

我的问题是:如何调用这个方法?

speechSynthesizer.speak(actions[0], onComplete: "here")

有多种选择。在这种情况下最简单的是考虑 onComplete 是最后一个关闭下一个:

speechSynthesizer.speak(actions[0]) {
  # onComplete code goes here
}

关于您问题中函数定义的评论。应该是

func speak(text:String, onComplete: () -> Void) {...} 

通过闭包。

speechSynthesizer.speak(actions.first) {
    // code to be executed after speaking
}

这与

相同
speechSynthesizer.speak(actions.first, onComplete: {
    // code to be executed after speaking
})

但显然,尾随闭包语法看起来更简洁。

解释:

  1. 第一部分()表示"a function without arguments",
  2. 第二部分-> ()表示"without return value"。