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)
答案 0 :(得分:1)
speakTool
属于Tool
类型,其属性onGraphicTouched
属于(Graphic) -> ()
类型,是一个以Graphic
为输入的函数/闭包并且不返回任何内容(Void
或()
)。
speakText(graphic:)
是指向上面定义的函数的函数指针。请注意,该函数具有所需的签名;需要Graphic
并且不返回任何内容。
因此speakTool.onGraphicTouched = speakText(graphic: )
会将指向该函数的指针指定给onGraphicTouched
,当触摸图形时,speakTool
会调用onGraphicTouched(someGraphic)
来调用speakText(graphic: someGraphic)
。