DevC DevC - 1 year ago 147
Swift Question

Insert function as parameter

Im unit testing my Alamofire code at the moment. Im trying to create a reusable method that I can pass in a status code and a method that will need to be invoked as parameters. I was thinking of using a closing block but the syntax is escaping me and it doesnt help that I have started with Swift. Here is an example:

func parseJsonResponse(response: Response <AnyObject, NSErrror>){

func test_networkRequest(withStatusCode statusCode: Int, /* parse function as parameter */) {

stub(isHost("")) { _ in

return OHHTTPStubsResponse(fileAtPath:OHPathForFile("wsresponse.json", self.dynamicType)!,
statusCode:statusCode, headers:["Content-Type":"application/json"])

Alamofire.request(.GET, "", parameters: ["foo": "bar"])
.responseJSON { response in
print(response.request) // original URL request
print(response.response) // URL response
print( // server data
print(response.result) // result of response serialization

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

//method should go here


I want to be able to make 'test_networkRequest' reusable in all my classes, and there will be different types of json to be parsed and handled in various ways. This is why I would like to be able to pass in a function as a parameter into 'test_networkRequest'.

I hope my end goal is clear, and I am open to suggestions if I am off track. :)

Answer Source

To create a block, do something like this:

class Foo {
    var block: (statusCode: Int) -> Void
    var optionalBlock: ((argA: Int, argB: String) -> Bool)? // in case you're curious

    init() {
        block = { (statusCode: Int) -> Void in
            // This is the block that can now be passed

You may want to think about your decision to use a block though. From the sentence "I want to be able to make 'test_networkRequest' reusable in all my classes..." it sounds like this may be better as a function in a superclass.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download