Swift:重用闭包定义(带类型)

前端之家收集整理的这篇文章主要介绍了Swift:重用闭包定义(带类型)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试创建一些闭包定义,我将在我的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 RealLifeClosure = (number: Int,factor: NSDecimalNumber!,key: String,upperCase: Bool) -> NSAttributedString

我基本上想要使用一个typealias作为快捷方式,所以我不必输入那么多.也许typealias不是正确的选择…还有另一个吗?

您没有在此代码中重写typealias声明,而是声明参数和返回类型:
AnonymousFunction({(another: Int) -> Bool in return another < 0})

令人高兴的是,Swift的类型推断允许您使用以下任何一种 – 选择最适合您的风格:

AnonymousFunction( { (number: Int) -> Bool in number < 0 } )
AnonymousFunction { (number: Int) -> Bool in number < 0 }
AnonymousFunction { (number) -> Bool in number < 0 }
AnonymousFunction { number -> Bool in number < 0 }
AnonymousFunction { number in number < 0 }
AnonymousFunction { $0 < 0 }
原文链接:https://www.f2er.com/swift/318988.html

猜你在找的Swift相关文章