【Swift 60秒】53 - Using closures as parameters when they accept parameters
创始人
2024-02-08 20:59:28

0x00 Lesson

This is where closures can start to be read a bit like line noise: a closure you pass into a function can also accept its own parameters.

We’ve been using () -> Void to mean “accepts no parameters and returns nothing”, but you can go ahead and fill the () with the types of any parameters that your closure should accept.

To demonstrate this, we can write a travel() function that accepts a closure as its only parameter, and that closure in turn accepts a string:

func travel(action: (String) -> Void) {print("I'm getting ready to go.")action("London")print("I arrived!")
}

Now when we call travel() using trailing closure syntax. our closure code is required to accept a string:

travel { (place: String) inprint("I'm going to \(place) in my car")
}

0x01 我的小作品

欢迎体验我的作品之一:小汉字-XHanzi
汉字书写入门,常用汉字 3800 个,二级字表 2200
App Store 搜索即可~


相关内容

热门资讯

存储芯片突然引爆!某一类型DR...   芯片行业有大变化?  据彭博社消息,包括马斯克和库克在内的科技行业领袖,正不断警告一场全球危机正...
今年已有143家企业递表港股I... 转自:财联社【今年已有143家企业递表港股IPO】财联社2月17日电,Wind数据显示,2026年以...
摩根士丹利:必和必拓上半年盈利... 格隆汇2月17日|摩根士丹利分析师Rahul Anand称,必和必拓的上半年业绩好于市场预期,其中利...
“音乐之城”绽放音乐魅力   本报讯(记者 于秋莹)中央广播电视总台2026年春节联欢晚会哈尔滨分会场“冰雪暖世界”节目播出后...
新春大集赴“莓”好之约   市民游客驻足品尝鲜甜草莓。  本报讯(张羽 记者 张大星文/摄)新年除夕,哈尔滨西城红场一楼新春...