[英]Swift completion block
我很难理解我遇到的问题。 为简化起见,我将使用UIView方法。 基本上,如果我写的方法
UIView.animateWithDuration(1, animations: {() in
}, completion:{(Bool) in
println("test")
})
它工作正常。 现在,如果我使用相同的方法,但创建一个这样的字符串:
UIView.animateWithDuration(1, animations: {() in
}, completion:{(Bool) in
String(23)
})
它停止工作。 编译器错误: 在调用中缺少参数'delay'的参数
现在,这是奇怪的部分。 如果我执行与失败的代码完全相同的代码,但只需添加如下的打印命令:
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仅由单个表达式组成时,它们具有隐式返回 。 这允许简洁的代码,例如:
reversed = sorted(names, { s1, s2 in s1 > s2 } )
在您的情况下,当您在此处创建字符串时:
UIView.animateWithDuration(1, animations: {() in }, completion:{(Bool) in
String(23)
})
你最终返回该字符串,这使得你的闭包签名:
(Bool) -> String
这不再匹配animateWithDuration
的签名所需的animateWithDuration
(这Missing argument for parameter 'delay' in call
错误中转换为Swift Missing argument for parameter 'delay' in call
的神秘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)
}
因为那里有两个表达式,而不仅仅是一个表达式; 隐式返回仅在闭包包含单个表达式时发生。 因此,该闭包不返回任何东西,并且与其签名相匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.