【问题标题】:Swift : Converting inline to trailing closures in functionSwift:在函数中将内联转换为尾随闭包
【发布时间】:2014-10-29 14:51:10
【问题描述】:

所以我定义了以下函数:

public typealias RESTClosure = (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void
public func queryAllFlightsWithClosure(completionHandler : RESTClosure) {       
// code ....  
}

我可以将此函数称为:

func myResponseHandler(response: NSURLResponse!, data: NSData!, error: NSError!) -> Void {
    // code ...
}

rest?.queryAllFlightsWithClosure(myResponseHandler)

然而,根据我对 Swift 的理解,如果函数的最后一个参数是闭包,它可以转换为尾随闭包……但我遇到了一些语法混乱:

尝试 #1

rest?.queryAllFlightsWithClosure() {
    println("Called with Closure")
}

错误: 元组类型 '(response: NSURLResponse!, data NSData!, error: NSError!)' 和 '()' 有不同数量的元素(3 vs. 0)

尝试 #2

rest?.queryAllFlightsWithClosure() (RESTClosure.self) {  // Xcode told me to add a .self
  //...code
}

错误: 调用中的参数 #1 缺少参数

我知道我已经很接近了......但是有人可以在这里帮助我吗?

【问题讨论】:

    标签: ios swift closures


    【解决方案1】:

    你的参数放在闭包里,因为只有一个参数,你甚至可以省略括号:

    rest?.queryAllFlightsWithClosure {
        (response: NSURLResponse!, data: NSData!, error: NSError!) in
    
        // code ...
    }
    

    如果您要访问self 或闭包内的任何属性,您需要将self 包含在捕获列表中,如下所示:

    rest?.queryAllFlightsWithClosure {
        [weak self] (response: NSURLResponse!, data: NSData!, error: NSError!) in
    
        // code ...
    
        // note that self is optional inside this closure b/c of [weak self]
        self?.doSomething()
    }
    

    【讨论】:

    • 我这里怎么不能用我的typalias?
    • 如果您使用类型别名,我认为您不能使用任何参数。如何使用您的别名引用版本中的 NSURLResponse 参数?
    • 您可以完全省略参数并使用速记($0$1 等),但我只将它们用于非常短的闭包。
    • 如果我想捕获任何其他变量,比如私有类变量?
    • 程序运行时不会释放类变量,因此在闭包中访问MyClass.propertyName 始终是安全的。
    【解决方案2】:

    这似乎可以编译

    rest?.queryAllFlightsWithClosure() { RESTClosure in
       // code ...        
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-11
      • 1970-01-01
      • 2020-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多