closure type inference - ShenYj/ShenYj.github.io GitHub Wiki
Multi-statement closure type inference
-
在此之前, 一些简单的场景中,我更习惯不展开闭包, 直接通过
$0
去简写,但某些复杂场景下并不适用, 就需要展开闭包显示定义闭包中的参数和返回值类型, 并添加in
关键字let scores = [100, 80, 85] let oldResults = scores.map { score -> String in if score >= 85 { return "\(score)%: Pass" } else { return "\(score)%: Fail" } }
-
在
Swift 5.7
下, 有了一些优化, 可以省略返回值类型, 自动推导了let scores = [100, 80, 85] let results = scores.map { score in if score >= 85 { return "\(score)%: Pass" } else { return "\(score)%: Fail" } }