My first post, so I apologize for lack of verbosity or knowledge. I am very new to Swift. I am using RxSwift to help concurrently run HTTP calls to my backend that I then zip up into a single observable that then is data bound to a view.
For part of the process, I am creating a Single from RxSwift that will then be either zipped or merged with other HTTP responses, depending on the view.
Intially I was getting a "Unable to expression type without a type annotation" with the closure defined inside function call of Single.create() so I broke the closure out. This is what the entire function looks like:
static func SendSingleRequest<ModelType>(_ request: any APIRequest, _ ModelType: some Decodable) -> Single<ModelType> {
let clo : (Single) -> Disposable = { single in
do{
self.session.dataTask(with: request.url) { (data, response, error) in
do {
let model = try JSONDecoder().decode(ModelType.self, from: data ?? Data())
single(.success(model))
} catch let jsonError as NSError {
print("Json decode failed: \(jsonError.localizedDescription)")
single(.failure(jsonError))
}
}
return Disposables.create()
}
};
return Single<ModelType>.create(subscribe: clo)
}
In essence, I am trying put the closure inside the .create function. I realize the function defintion of .create() include the @escaping keyword, but that doesn't seem to be an issue. Please correct me if I'm wrong.
Finally, an error saying, "Unable to infer closure type without a type annotation." in the closure definition line (line 2) is popping up, when I feel as though I am defining it, and, in all cases, I am returning a Disposable. Again, I am very new to swift.
How do I avoid this error despite explicitly defining the types?
I've have tried different permutaions of function definintions, honestly trial and error. Wasn't expecting much.
I've hasve tried defining the closure in different places, which doesn't change the code in theory, but I was hoping.
I have tried rearranging the overall structure of what is getting passed into this function so I don't have to deal with certain variables, but this is about as simple as I can make it.
Overall, I've been doing a lot of guess and check AFTER reading about the problem, and I either run into another type error or normal error.
You aren't defining the limits of your
ModelType. It must be Decodable. This will compile:However is it woefully inadequate for what you are trying to do (and in Swift, function names always start with a lower case letter.)
URLinstead of an entireURLRequestlimits your ability to do the standard REST calls.Your best bet would be to use RxCocoa's
datafunction. It handles all the heavy lifting for you. So a better translation would be something like:Better still would be to use URLRequest instead of just URL. Also, what about when you want the raw data instead of using JSON? (For example when downloading images.)
Something like this would be far better:
I use something very much like the above in my CLE library.