【发布时间】:2015-03-04 10:25:06
【问题描述】:
我正在尝试创建一些我将在我的 iOS 应用程序中大量使用的闭包定义。所以我想使用类型别名,因为它似乎是最有前途的......
我做了一个小 Playground 示例,详细说明了我的问题
// Here are two tries for the Closure I need
typealias AnonymousCheck = (Int) -> Bool
typealias NamedCheck = (number: Int) -> Bool
// This works fine
var var1: AnonymousCheck = {
return $0 > 0
}
var1(-2)
var1(3343)
// This works fine
var var2: NamedCheck = {
return $0 > 0
}
var2(number: -2)
var2(number: 12)
// But I want to use the typealias mainly as function parameter!
// So:
// Use typealias as function parameter
func NamedFunction(closure: NamedCheck) {
closure(number: 3)
}
func AnonymousFunction(closure: AnonymousCheck) {
closure(3)
}
// This works as well
// But why write again the typealias declaration?
AnonymousFunction({(another: Int) -> Bool in return another < 0})
NamedFunction({(another: Int) -> Bool in return another < 0})
// This is what I want... which doesn't work
// ERROR: Use of unresolved identifier 'number'
NamedFunction({NamedCheck in return number < 0})
// Not even these work
// ERROR for both: Anonymous closure arguments cannot be used inside a closure that has exlicit arguments
NamedFunction({NamedCheck in return $0 < 0})
AnonymousFunction({AnonymousCheck in return $0 < 0})
是我遗漏了什么还是 Swift 不支持它? 谢谢
编辑/添加:
以上只是一个简单的例子。在现实生活中,我的 typealias 更复杂。比如:
typealias RealLifeClosure = (number: Int, factor: NSDecimalNumber!, key: String, upperCase: Bool) -> NSAttributedString
我基本上想使用 typealias 作为快捷方式,所以我不必输入那么多。也许 typealias 不是正确的选择……还有其他的吗?
【问题讨论】:
标签: swift closures type-alias