within unreachable try thrown throwing occur how functions example errors error catch calls because are swift error-handling try-catch swift3

unreachable - Manejo de errores en Swift 3



try catch swift 4 example (1)

Estoy migrando mi código a Swift 3 y veo un montón de las mismas advertencias con mis bloques do / try / catch. Quiero comprobar si una tarea no devuelve nada y luego imprimir algo en la consola si no funciona. El bloque catch dice que "es inalcanzable porque no se generan errores en el bloque ''do''". Me gustaría detectar todos los errores con un bloque catch.

let xmlString: String? do{ //Warning for line below: "no calls to throwing function occurs within ''try'' expression try xmlString = String(contentsOfURL: accessURL, encoding: String.Encoding.utf8) var xmlDict = XMLDictionaryParser.sharedInstance().dictionary(with: xmlString) if let models = xmlDict?["Cygnet"] { self.cygnets = models as! NSArray } //Warning for line below: "catch block is unreachable because no errors are thrown in ''do'' block } catch { print("error getting xml string") }

¿Cómo escribiría un bloque try catch adecuado que manejaría los errores de asignación?


Una forma de hacerlo es arrojando sus propios errores para encontrar nada.

Al tener este tipo de tu propio error:

enum MyError: Error { case FoundNil(String) }

Puedes escribir algo como esto:

do{ let xmlString = try String(contentsOf: accessURL, encoding: String.Encoding.utf8) guard let xmlDict = XMLDictionaryParser.sharedInstance().dictionary(with: xmlString) else { throw MyError.FoundNil("xmlDict") } guard let models = xmlDict["Cygnet"] as? NSArray else { throw MyError.FoundNil("models") } self.cygnets = models } catch { print("error getting xml string: /(error)") }