简体   繁体   English

Swift:将函子传递给函子称为传递的函子

[英]Swift: passing a func into a func calls the passed in func

How do I pass a function into another function without causing the passed in function to get called the moment it is read as an argument? 我如何将一个函数传递给另一个函数,而又不会在将传递的函数作为参数读取时被调用?

Here is an example of one function getting called simply by being an argument. 这是一个简单地被一个参数调用的例子。

func second() {
    print("second")
}

func first(_: ()) {
    print("first")
}

first(second())

-------console output--------
second
first

I want to pass second into first so that I can call second() somewhere inside of first's body, but as you can see, second gets called immediately simply by being an argument. 我想将second传递给first,以便可以在first体内的某个地方调用second(),但是正如您所看到的,second只是通过作为参数立即被调用。

func first(_: ()) {
    print("first")
}

This is a function that takes a Void as its argument (and ignores it). 此函数将Void作为其参数(并忽略它)。 Void is a typealias for the empty tuple () . Void是空元组()的类型别名。 You meant: 你的意思是:

func first(f: () -> Void) {}

That is a function that takes a function that returns nothing (and calls its parameter f rather than ignoring it). 该函数接受不返回任何内容的函数(并调用其参数f而不是忽略它)。

first(second())

This calls second and then passes the result to first . 这将调用second ,然后将结果传递给first You meant: 你的意思是:

first(second)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM