【问题标题】:Swift: Understanding Closure LogicSwift:理解闭包逻辑
【发布时间】:2022-01-09 15:47:37
【问题描述】:
import UIKit
func study(reviseNotes: (String) -> Void) {
    print("1")
    let notes = "Napoleon was a short, dead dude."
    print("2")
    for _ in 1...10{
        reviseNotes(notes)
    }
}

study(reviseNotes:{(notes:String) in
    print("3")
    print("I'm reading my notes \(notes)")
})

reviseNotes(notes)如何调用study( reviseNotes: {(notes:String)} )?**
(打印用于调试。)

我在尝试理解逻辑?

【问题讨论】:

  • reviseNotes(String) -> Void,所以它就像一个“带有String 参数的迷你函数”。因此,当您执行reviseNotes(notes) 时,您是在告诉他调用该方法。 { (notes:String) in ... },这就是你的实现。这是一个闭包/回调/块,如果您有任何其他编码知识,或者名称可能会让您更好地理解它(callback 通常可以理解)。

标签: swift closures


【解决方案1】:

reviseNotes(notes) 没有调用整个study( reviseNotes: {(notes:String)} )
那只是触发你发送的参数,只意味着reviseNotes: {(notes:String)}

在部分中执行相同的过程。

import UIKit
func study(reviseNotes: (String) -> Void) {
    print("1")
    let notes = "Napoleon was a short, dead dude."
    print("2")
    for _ in 1...10{
        reviseNotes(notes)
    }
}

var myClosure = { (notes:String) in
    print("3")
    print("I'm reading my notes \(notes)")
}
study(reviseNotes: myClosure)

每当reviseNotes(for循环内10次)时,都会触发;
它只是执行 myClosure 变量。

在当前情况下,
闭包获取字符串信息,该信息可以在闭包体中使用。

有时我们需要闭包中的信息,无论何时调用它。
在这种情况下,闭包的返回类型不是Void / ()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 2010-10-28
    • 2017-07-13
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    相关资源
    最近更新 更多