在“学习Swift”一书中(Wagner),这个关于闭包的例子(特别是闭包作为参数):
func firstInNumbers(numbers: [Int], passingTest: (number: Int) -> Bool -> Int? {
for number in numbers {
if passingTest(number: number) {
return number
}
}
return nil
}
let numbers = [1,2,3,4,5]
func greaterThanThree(number: Int) -> Bool {
return number > 3
}
var firstNumber = firstInNumbers(numbers, greaterThanThree)
println(firstNumber)
<code>
那么,为什么if语句中的(number:number)语法?
答案 0 :(得分:0)
第二个number:
passingTest(number: number)
^^^^^^^
添加了,因为闭包passingTest
的类型是(number: Int) -> Bool
。请参阅类型中的number:
?它指定了在调用闭包时需要放置的参数标签。参数标签放在那里的原因可能是因为作者试图更清楚,但IMO已经非常清楚该闭包的参数是做什么的。另外,标签number
并没有真正增加太多意义......所以第一个number:
实际上只是为了#34;美学&#34;。也许它让初学者更容易理解?
但是,在Swift 4中,您无法向闭包类型添加参数标签。在Swift 4中,方法如下:
func firstInNumbers(numbers: [Int], passingTest: (Int) -> Bool) -> Int? {
for number in numbers {
if passingTest(number) {
return number
}
}
return nil
}
答案 1 :(得分:0)
让你感到困惑的是,闭包的参数名称“number”与你传递给闭包的变量相同。
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12;
$buildId = "%teamcity.build.id%"
function TeamCityBuildStatus
{
param
(
[string] $ServerUrl,
[string] $UserName,
[string] $Password,
[string] $BuildId
)
$client = New-Object System.Net.WebClient
$pair = "$($UserName):$Password"
$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))
$client.Headers.Add("Authorization", "Basic $encodedCreds")
$url = "https://$ServerUrl/httpAuth/app/rest/builds/$buildId/status"
$status = $client.DownloadString($url)
return $status -eq "SUCCESS"
}
$status = TeamCityBuildStatus -ServerUrl $teamcityUrl -UserName $teamcityUser -Password $teamcityPass -BuildId $buildId
Write-Host "##teamcity[setParameter name='Status' value='$status']"
如果您使用其他名称,也许更容易区分,如:
//The parameter name "number" here -----------------V
func firstInNumbers(numbers: [Int], passingTest: (number: Int) -> Bool -> Int? {
//And the variable "number" here -\
// V---------------------------/
for number in numbers {
if passingTest(number: number) {
return number
}
}
return nil
}
在Swift 4中,无法标记闭包参数。此外,原帖中还有一些小的语法错误。更正语法错误,并将闭包示例带到Swift 4,完整示例如下所示:
func firstInNumbers(numbers: [Int], passingTest: (number: Int) -> Bool -> Int? {
for n in numbers {
if passingTest(number: n) {
return n
}
}
return nil
}