LoginSignup
0
0

More than 5 years have passed since last update.

Swift 5 Brand New Result Type: Write Cleaner API Code

Posted at
 struct Course: Decodable {
    let id: Int
    let name: String
    let imageUrl: String
    let number_of_lessons: Int
  }

  func start() {

    fetchCoursesJSON { (res) in
      switch res {
      case .success(let courses):
        courses.forEach({ (course) in
          print(course.name)
        })
      case .failure(let err):
        print("failed", err)
      }
    }
  }

  func fetchCoursesJSON(completion: @escaping (Result<[Course], Error>) -> ()) {
    let urlString = ""
    guard let url = URL(string: urlString) else { return }

    URLSession.shared.dataTask(with: url) { (data, resp, err) in

      if let err = err {
        completion(.failure(err))
        return
      }

      // successful
      do {
        let courses = try JSONDecoder().decode([Course].self, from: data!)
        completion(.success(courses))
      } catch let jsonError {
        completion(.failure(jsonError))
      }

    }.resume()

  }
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0