【问题标题】:Nested function in swift 3swift 3中的嵌套函数
【发布时间】:2017-05-04 07:15:50
【问题描述】:

我正在查看 Alamofire 文档并找到以下代码

 Alamofire.request("https://httpbin.org/get").responseJSON { response in
debugPrint(response)

if let json = response.result.value {
    print("JSON: \(json)")
}
}

好像函数写成这样

Class.Function().Function{
}

这叫做嵌套函数吗?如果是这样,我将如何创建一个简单的嵌套函数来了解语法

【问题讨论】:

标签: swift methods syntax swift3 alamofire


【解决方案1】:

这不是一个嵌套函数,而是一个函数链。

class Alamofire {
    static func request(_ url: String)->Request {
        //... code ...
        return aRequest
    }
}

class Request {
    func responseJson(completion: (response: Response)->()) {
        //code
    }
}

所以这就是正在发生的事情。 Alamofire 的 request 函数返回一个 Request 对象,该对象具有 responseJson 函数,该函数接受一个闭包作为参数。

swift中如果闭包参数是最后一个,可以通过去掉参数名来合成函数调用,将闭包定义为函数这样就可以了

Alamofire.request("whatever").responseJson(completion: { (response) in 
    //whatever
})

和做的一模一样

Alamofire.request("whatever").responseJson(){ (response) in 
    //whatever
}

这是一个尾随闭包。您可以在“尾随闭包”段落中找到有关它的更多信息here

希望对你有帮助

【讨论】:

    【解决方案2】:

    它是Method chaining,最后一个是尾随闭包的语法。

    闭包是可以传递的独立功能块 并在您的代码中使用。

        func someFunctionThatTakesAClosure(closure: () -> Void) {
        // function body goes here
    }
    
    // Here's how you call this function without using a trailing closure:
    
    someFunctionThatTakesAClosure(closure: {
        // closure's body goes here
    })
    
    // Here's how you call this function with a trailing closure instead:
    
    someFunctionThatTakesAClosure() {
        // trailing closure's body goes here
    }
    

    有关闭包的更多信息,请阅读it

    【讨论】:

      猜你喜欢
      • 2016-12-23
      • 2015-12-05
      • 1970-01-01
      • 2014-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多