问题
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