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"
        }
    }
⚠️ **GitHub.com Fallback** ⚠️