Introducci贸n a Swift y XCode
Swift y el ecosistema Apple
Instalaci贸n y configuraci贸n de XCode
Quiz: Introducci贸n a Swift y XCode
Fundamentos de programaci贸n iOS
Variables, constantes y tipos de datos b谩sicos
Condicionales
Funciones
Tipos de datos opcionales
Arreglos: append, insert, como crearlas
Arreglos: validar, editar y agregar una lista dentro de otra lista
Conjuntos: como agregar o eliminar elementos
Conjuntos: principales operaciones entre conjuntos
Diccionarios
Recorridos parte 1: while
Recorridos parte 2: for
Recorridos parte 3: los retos
Quiz: Fundamentos de programaci贸n iOS
POO en iOS
Programaci贸n orientada a objetos en iOS
Structs
Clases y herencia
Enums
Protocolos
Funciones de arreglos (filter, map, reduce)
Funciones de arreglos parte 2 (filter, map, reduce): playground
Quiz: POO en iOS
Manejo de errores y programaci贸n segura
Manejo de errores y programaci贸n segura
Propagaci贸n de errores
Do, try, catch
Quiz: Manejo de errores y programaci贸n segura
Programaci贸n en el ecosistema de Apple
Siguientes pasos para el desarrollo en iOS
You don't have access to this class
Keep learning! Join and start boosting your career
Creating custom errors in Swift is essential for improving error handling in your applications. This allows you to provide more descriptive error messages that benefit both developers and end users. Let's start by defining a custom error in Swift. We will use the enum
keyword to create these errors, and have them implement the Error
and LocalizedError
protocols.
To create a custom error enum, start with defining an enum
that implements the appropriate protocols. This will allow you to specify different error cases that you want to handle in your application.
public enum ManagerError: Error, LocalizedError { case studentNotAddError case subjectNotAssignedError case reportNotFoundError case maxStudentsReachedError(max: Int) public var errorDescription: String? { switch self { case .studentNotAddError: return "Student could not be added." case .subjectNotAssignedError: return "Could not assign subject." case .reportNotFoundError: return "The report could not be found, since the list of students is empty." case .maxStudentsReachedError(let max): return "The maximum number of students \(max) has been reached." } } } } } }
The LocalizedError
protocol allows defining an optional errorDescription
property. This property provides more detailed error descriptions, which can be used in the user interface or in system feedback. We use a switch
to return descriptions based on each enum
case.
Once errors are defined, it is crucial to know when and how to throw them in your methods. In Swift, we use the throws
keyword to indicate that a method can throw an error.
Before throwing errors, define which methods in your protocol can cause errors. Here we use the throws
modifier in the method declaration. Look at an example where a method to insert students throws an error if something goes wrong.
func insertStudent(_ student: Student) throws { if student == nil { throw ManagerError.studentNotAddError } // Check the maximum number of students before adding a new one if students.count >= maxStudents { throw ManagerError.maxStudentsReachedError(max: maxStudents) } students.append(student) }
In our example of the student manager(StudentsManager
), we throw specific errors depending on the operations attempted.
func assignSubjectToStudent(_ subject: Subject, student: Student) throws { guard student.subjects.contains(subject) else { throw ManagerError.subjectNotAssignedError } student.subjects.append(subject) } func generateReport() throws -> String { guard !students.isEmpty else { throw ManagerError.reportNotFoundError } // Generate and print reports }
Handling and catching thrown errors will improve the stability and user experience in your application. Proper implementation of these techniques will allow you to catch specific errors efficiently.
do-catch
to handle errors: Capture and handle errors in the catch
block, providing a controlled flow of execution.errorDescription
.Contributions 0
Questions 0
Want to see more contributions, questions and answers from the community?