如何在不传入值的情况下调用带参数的函数? [斯威夫特游乐场]

时间:2017-06-30 16:42:36

标签: swift swift-playground

Swift Playground提供了以下代码。如何在不传递参数的情况下调用speakText(graphic :)? (显然,图形已经放在代码的另一部分中)

// Speak the text of graphic.
func speakText(graphic: Graphic) {
    speak(graphic.text)
}
func addGreeting(touch: Touch) {
    if touch.previousPlaceDistance < 60 { return }
    let greetings = ["howdy!", "hello", "hi", "ciao", "yo!", "hey!",       "what’s up?"]
    let greeting = greetings.randomItem
    let graphic = Graphic(text: greeting)
    graphic.textColor = #colorLiteral(red: 0.9686274529, green: 0.78039217, blue: 0.3450980484, alpha: 1)
    graphic.fontName = .chalkduster
    scene.place(graphic, at: touch.position)
    graphic.rotation = randomDouble(from: -30, to: 30)
}
// Create and add Speak tool.
let speakTool = Tool(name: "Speak", emojiIcon: "")
speakTool.onGraphicTouched = speakText(graphic: )
scene.tools.append(speakTool)

1 个答案:

答案 0 :(得分:1)

speakTool属于Tool类型,其属性onGraphicTouched属于(Graphic) -> ()类型,是一个以Graphic为输入的函数/闭包并且不返回任何内容(Void())。

speakText(graphic:)是指向上面定义的函数的函数指针。请注意,该函数具有所需的签名;需要Graphic并且不返回任何内容。

因此speakTool.onGraphicTouched = speakText(graphic: )会将指向该函数的指针指定给onGraphicTouched,当触摸图形时,speakTool会调用onGraphicTouched(someGraphic)来调用speakText(graphic: someGraphic)

您可以在Apple's Swift Guide.

中的功能类型部分详细了解相关内容