我有一个泛型类,其函数使用<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<ul>
<li ng-repeat="get_date in dates">
<h2>{{get_date.date}}</h2>
<h4>{{get_date.data}}</h4>
</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.dates = [{date:"1",data:"One"},{date:"2",data:"Two"},{date:"3",data:"Three"}];
});
</script>
</body>
</html>
从远程URL获取json响应,并使用Alamofire
库进行序列化。
该函数的代码是:
AlamofireObjectMapper
现在,在实现部分中,我使用了以下代码:
class func getDataFromNetwork<T: Mappable>(urlString: String, completion: @escaping (T?, NSError) -> Void) {
Alamofire.request(urlString).responseObject{ (response: DataResponse<T, NSError>) in
guard response.result.isSuccess else {
print("Error while Fetching: \(response.result.error)")
completion(nil, response.result.error)
return
}
if let responseObject = response.result.value {
print(responseObject)
completion(responseObject, nil)
}
}
}
Fetcher是包含 Fetcher.getDataFromNetwork(urlString: "https://my.json.url") { NHRootClass?, error in
}
的类,NHRootClass是类getDataFromNetwork()
。我无法编写实现部分来获取Mappable
的响应。
这是班级Generic Function
。
NHRootClass