我很难理解我遇到的问题。 为了简化,我将使用 UIView 方法。 基本上,如果我编写方法
UIView.animateWithDuration(1, animations: {() in
}, completion:{(Bool) in
println("test")
})
它工作正常。 现在,如果我使用相同的方法,但创建一个像这样的字符串:
UIView.animateWithDuration(1, animations: {() in
}, completion:{(Bool) in
String(23)
})
它停止工作。编译器错误:调用中缺少参数“延迟”的参数
现在,这是奇怪的部分。如果我执行与失败代码完全相同的代码,但只需添加如下打印命令:
UIView.animateWithDuration(1, animations: {() in
}, completion:{(Bool) in
String(23)
println("test")
})
它又开始工作了。
我的问题基本上是一样的。我的代码:
downloadImage(filePath, url: url) { () -> Void in
self.delegate?.imageDownloader(self, posterPath: posterPath)
}
不起作用。但如果我改成。
downloadImage(filePath, url: url) { () -> Void in
self.delegate?.imageDownloader(self, posterPath: posterPath)
println("test")
}
甚至:
downloadImage(filePath, url: url) { () -> Void in
self.delegate?.imageDownloader(self, posterPath: posterPath)
self.delegate?.imageDownloader(self, posterPath: posterPath)
}
它工作正常。 我不明白为什么会这样。我几乎可以接受这是一个编译器错误。
最佳答案
Swift 中的闭包有 implicit returns 当它们仅由一个单个表达式 组成时。这允许像这样的简洁代码:
reversed = sorted(names, { s1, s2 in s1 > s2 } )
在您的情况下,当您在此处创建字符串时:
UIView.animateWithDuration(1, animations: {() in }, completion:{(Bool) in
String(23)
})
你最终会返回那个字符串,这就是你闭包的签名:
(Bool) -> String
这不再符合 animateWithDuration
签名的要求(转换为 Swift 的神秘 Missing argument for parameter 'delay' in call
错误,因为它找不到一个适当的签名来匹配)。
一个简单的解决方法是在闭包末尾添加一个空的 return 语句:
UIView.animateWithDuration(1, animations: {() in}, completion:{(Bool) in
String(23)
return
})
使您的签名成为应有的样子:
(Bool) -> ()
你的最后一个例子:
downloadImage(filePath, url: url) { () -> Void in
self.delegate?.imageDownloader(self, posterPath: posterPath)
self.delegate?.imageDownloader(self, posterPath: posterPath)
}
之所以有效,是因为那里有两个表达式,而不仅仅是一个;隐式返回仅在闭包包含单个表达式时发生。因此,该闭包不会返回任何与其签名相匹配的内容。
关于ios - 快速完成 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25955272/