How is it possible to call a function with parameters without passing in values? [Swift Playground]

有些话、适合烂在心里 提交于 2019-12-12 05:28:21

问题


Swift Playground provided the following code. How's the speakText(graphic: )called without passing in parameters? (Obviously graphic is already placed in another segment of the code)

// 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:


speakTool is of type Tool which has a property onGraphicTouched that is of type (Graphic) -> () which is a function/closure that takes a Graphic as input and returns nothing (Void or ()).

speakText(graphic:) is a function pointer to your function defined above. Note that that function has the required signature; it takes a Graphic and returns nothing.

So speakTool.onGraphicTouched = speakText(graphic: ) assigns a pointer to the function to onGraphicTouched and when the graphic is touched, the speakTool will call onGraphicTouched(someGraphic) which will call speakText(graphic: someGraphic).

You can read more about this in the section on Function Types in Apple's Swift Guide.



来源:https://stackoverflow.com/questions/44851319/how-is-it-possible-to-call-a-function-with-parameters-without-passing-in-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!