i'm migrating code on swift 3 , see bunch of same warnings do/try/catch blocks. want check if assignment doesn't return nil , print out console if doesn't work. catch block says "is unreachable because no errors thrown in 'do' block". want catch errors 1 catch block.
let xmlstring: string? do{ //warning line below: "no calls 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 line below: "catch block unreachable because no errors thrown in 'do' block } catch { print("error getting xml string") }
how write proper try catch block handle assignment errors?
one way can throwing own errors on finding nil.
with having sort of own error:
enum myerror: error { case foundnil(string) }
you can write this:
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)") }
Comments
Post a Comment