You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift闭包实现两数求和时禁用代码编译错误求助

Fixing Your Swift Closure Compile Error

Hey there! Let's break down and fix that compile error in your closure call. You've got the right idea with the closure definition, but there are two small syntax mistakes tripping you up:

1. Duplicate let Keyword

Your line let res = let closure(...) has an extra let right before closure—this is unnecessary. You only use let when declaring a new constant, not when assigning a value to one you're already creating.

2. Unneeded Parameter Labels

The closure you defined ((Int, Int) -> Int) doesn't have external parameter labels, so you can't use number1: and number2: when calling it. Closures default to no external labels unless you explicitly define them.


Correct Working Code

Here's how to fix the call, plus a complete example:

// Your original (correct) closure definition
let closure: (Int, Int) -> Int = { return $0 + $1 }
// Or the shorter, idiomatic Swift version (single-expression closures omit return):
// let closure: (Int, Int) -> Int = { $0 + $1 }

// Define your input numbers
let number1 = 10
let number2 = 20

// Properly call the closure and assign the result
let res = closure(number1, number2)

print(res) // Outputs: 30

Bonus: Using Parameter Labels with Closures

If you want to use named parameters when calling the closure, you need to specify external labels in the closure's type definition:

// Closure with explicit external parameter labels
let closureWithLabels: (number1: Int, number2: Int) -> Int = { num1, num2 in
    return num1 + num2
}

// Now you can use the labels when calling
let res = closureWithLabels(number1: 15, number2: 25)
print(res) // Outputs: 40

内容的提问来源于stack exchange,提问作者Prabs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 03:52:48