A
A
Andrew2021-01-13 14:42:10
Swift
Andrew, 2021-01-13 14:42:10

How to pass a struct name as a function parameter?

Good afternoon.

There is a method like:

static func fetch(url: String, completion: @escaping (Result<[Supplier], Error>) -> Void) {
        guard let url = URL(string: url) else { return }
        var urlRequest = URLRequest(url: url)
        urlRequest.httpMethod = "GET"
        self.setToken(urlRequest: &urlRequest, token: "6dc3d1de41126000d08a7ec4283e16d2ca13a203")
        
        URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
            DispatchQueue.main.async {
                if let error = error {
                    completion(.failure(error))
                    return
                }
                guard let data = data else { return }
                do {
                    let suppliers = try JSONDecoder().decode([Supplier].self, from: data)
                    completion(.success(suppliers))
                } catch {
                    completion(.failure(error))
                }
                
                
            }
        }.resume()
    }


I want to make it universal. Those. pass as a parameter what specific array of strakts should be returned.
Something like this:

static func fetch(url: String, completion: @escaping (Result<[ structname ], Error>) -> Void) {
...
let resultSet = try JSONDecoder().decode([ structname ].self, from :data)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
briahas, 2021-01-13
@G_r_i_n_v_i_c_h

Look towards Generic. It seems to be what you need.
updated
Yep, I get it... try this

func GetTools(currentURLRequest: String, completion:(Result<ToolDetailsSearchResult, Error>)->Void
    ...
    fetch(urlRequest: currentURLRequest) { (_ result: Result<ToolDetailsSearchResult, Error>) in
         ...
    }
}

The meaning of the problem is that you did not specify the final type of the variable. It is necessary to explicitly specify the type when using it, then it understands what to translate into.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question