【发布时间】:2016-01-08 21:37:18
【问题描述】:
我只是在玩 2.0 版中的新错误处理。我现在有了以下功能:
func decodeHTML(HTML: String) throws {
guard let remove : String? = HTML.componentsSeparatedByString("<div id=\"loading\" style=\"display: none;\">")[0] else { throw DecodeError.MatchError }
guard var splitter : [String]? = remove!.componentsSeparatedByString("<div class=\"info\">") else { throw DecodeError.MatchError }
if splitter!.count > 0 { splitter!.removeFirst() }
if splitter!.count > 0 { splitter!.removeLast() }
if splitter!.count > 0 {
for HTMLmessage in splitter! {
guard var splitter2 : [String]? = HTMLmessage.componentsSeparatedByString("</td><td>Besked fra ") else { throw DecodeError.MatchError }
guard let author : String? = (splitter2![1].componentsSeparatedByString("</tr>"))[0] else { throw DecodeError.MatchError }
guard let date : String? = (splitter2![0].componentsSeparatedByString("<td width=\"25%\">"))[1] else { throw DecodeError.MatchError }
guard let title : String? = HTMLmessage.componentsSeparatedByString("\"><b>")[1].componentsSeparatedByString("</b></a></td></tr>")[0] else { throw DecodeError.MatchError }
guard var string : String? = HTMLmessage.componentsSeparatedByString("</a></td></tr><tr><td colspan=2>")[1].componentsSeparatedByString("</td></tr></table></div>")[0] else { throw DecodeError.MatchError }
string = string!.stringByReplacingOccurrencesOfString("</p><p>", withString: "\n")
string = string!.stringByReplacingOccurrencesOfString("<[^>]+>", withString: "", options: .RegularExpressionSearch, range: nil)
self.messages.append(message(author, date, title, string))
}
} else {
throw DecodeError.MatchError
}
}
但我想知道,我真的必须在每次出现问题时都保持警惕吗?如果其中一行失败,是否有更简单的方法来引发错误?
【问题讨论】:
-
由于您抛出相同的错误,您可以将所有条件放在一个保护块中。
-
请注意(至少在 Swift 2.0 中)
componentsSeparatedByString()返回一个 非可选[String]数组。如果数组太短,下标(使用[0]、[1]...)也不会返回可选值,但会因运行时异常而中止。 – 换句话说,您的大多数受保护绑定都没有按您可能期望的那样工作。 -
如果你删除所有显式类型注释,例如
: String?,让编译器推断类型,你的问题会变得更加明显。 -
顺便说一句。你的“解码”方法对我来说看起来很脆弱。使用适当的 HTML 解析库可能会更好。
-
考虑使用基于
libxml的HTML解析器