【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 搜索即可~


相关内容

热门资讯

山东阳谷县通报:一公司石蜡料场... 情况通报2026年6月13日17时38分,山东阳谷华泰化工股份有限公司石蜡料场起火,市县立即组织力量...
采纳科技2025年参保人数14... 6月14日消息,据天眼查数据显示,采纳科技股份有限公司2025年参保人数为149人,较2024年披露...
劣质“迪卡侬”流向全国,有店铺... 据蓝鲸新闻6月14日报道,近日,记者接到大量消费者买到迪卡侬劣质产品的举报线索。记者在一些电商平台以...
市值暴增790亿!PCB“卖铲... 进入2026年,大族激光在资本市场上“一路长虹”。数据统计显示,截至最新收盘,大族激光年内股价涨幅突...
微光成炬!联动多方资源,这场公... (来源:上观新闻)2026年6月14日是第23个世界献血者日。近日,徐汇区漕河泾街道红十字会联合徐汇...