DevC DevC - 4 months ago 37
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>){
//parsing
}

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

stub(isHost("https://httpbin.org")) { _ in

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

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


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

//method should go here
self.parseJsonResponse(response)


}
}


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

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.