Home > Software design >  Swift Playground "Expressions are not allowed at the top level"
Swift Playground "Expressions are not allowed at the top level"

Time:07-20

I know it is impossible to call function from here in real app project. But in playground it was possible. What can I do now?

enter image description here

CodePudding user response:

You can try using class

like this:

struct Dummy: Decodable {
    let userId: Int
    let id: Int
    let title: String?
    let body: String?
}

final class APIHandler{
    
    static let shared = APIHandler()
    private init () {}
    
    func get<T: Decodable>(_ type: T.Type, completion:@escaping (Result<T,Error>)->Void) {
        
        guard let url = URL(string:"https://jsonplaceholder.typicode.com/posts" ) else {return}
        
        let task = URLSession.shared
        task.dataTask(with: url) {  data, response, error in
            
            if let error = error {
                completion(.failure(error))
            }
            
            if let data = data {
                
                do {
                    let json =   try JSONDecoder().decode(T.self, from: data)
                    completion(.success(json))
                } catch let error {
                    print("Error with Data : \(error)")
                    completion(.failure(error))
                }
                
            }
            
        }.resume()
        
    }
}

and test it:

APIHandler.shared.get([Dummy].self) { result in
    switch result {
    case .success(let res):
        print("response: ", res)
    case .failure(let error):
        print(error)
    }
}
  • Related