gpt4 book ai didi

swift - 如何在不传递值的情况下调用带参数的函数? [ swift Playground ]

转载 作者:行者123 更新时间:2023-11-28 15:29:45 25 4
gpt4 key购买 nike

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)

最佳答案

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

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

因此 speakTool.onGraphicTouched = speakText(graphic: ) 将指向函数的指针分配给 onGraphicTouched,当图形被触摸时,speakTool 将调用 onGraphicTouched(someGraphic),这将调用 speakText(graphic: someGraphic)

您可以在 Apple's Swift Guide. 中关于函数类型 的部分阅读更多相关信息

关于swift - 如何在不传递值的情况下调用带参数的函数? [ swift Playground ],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44851319/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com