2016-04-28 4 views
0

私のAlamofireコードをテストしています。私はステータスコードとパラメータとして呼び出す必要があるメソッドで渡すことができる再利用可能なメソッドを作成しようとしています。私は閉鎖ブロックを使用することを考えていましたが、構文が私を逃れていて、Swiftで始まったのは助けになりません。次に例を示します。パラメータを関数として挿入します。

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) 


    } 
} 

私は「test_networkRequest」再利用可能なすべての私のクラスでは作ることができるようにしたい、とさまざまな方法で解析され、処理されるJSONの異なる種類があるでしょう。このため、関数として 'test_networkRequest'にパラメータとして渡すことができるようにしたいと考えています。

私の最終目標がはっきりしていることを願っています。 :)

答えて

1

このような何か、ブロックを作成するには:あなたががブロックを使用するためにあなたの決定について考えてよいでしょう

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 
     } 
    } 
} 

を。 「すべてのクラスでtest_networkRequestを再利用できるようにしたい」という文章から、スーパークラスの関数としてはこれが良いかもしれないように思えます。

関連する問題