【问题标题】:How is it possible to call a function with parameters without passing in values? [Swift Playground]如何在不传入值的情况下调用带参数的函数? [迅捷游乐场]
【发布时间】:2017-06-30 16:42:36
【问题描述】:

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)

【问题讨论】:

    标签: swift swift-playground


    【解决方案1】:

    speakToolTool 类型,它有一个onGraphicTouched 类型的属性(Graphic) -&gt; (),它是一个函数/闭包,它接受Graphic 作为输入并且什么都不返回(Void 或@987654329 @)。

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

    所以speakTool.onGraphicTouched = speakText(graphic: ) 将指向函数的指针分配给onGraphicTouched,当触摸图形时,speakTool 将调用onGraphicTouched(someGraphic),而speakText(graphic: someGraphic) 将调用。

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

    【讨论】:

    猜你喜欢
    • 2020-09-10
    • 2020-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-25
    • 2018-07-13
    • 2023-02-23
    相关资源
    最近更新 更多