如何处理失败的可选绑定

问题描述

我正在尝试从字符串创建新的URL数据类型,该字符串返回可选值。当我尝试可选绑定时,缩进代码永远不会执行。

如何捕获可选绑定失败的错误或原因?

let newString = "http://somehost:1337/parse/classes/CompEntry?where={\"CompID\":{\"__type\":\"Pointer\",\"className\":\"Competition\",\"objectId\":\"CXy40U65Z9\"}}"
if let url = URL(string: newString) {
    print("here") // NEVER GETS EXECUTED
}

是因为字符串中的转义字符“吗?

解决方法

只需在IF控制流程中添加其他内容

let newString = "http://somehost:1337/parse/classes/CompEntry?where={\"CompID\":{\"__type\":\"Pointer\",\"className\":\"Competition\",\"objectId\":\"CXy40U65Z9\"}}"
    if let url = URL(string: newString) {
        print("here") // NEVER GETS EXECUTED
    } else {
        print("here") // EXECUTED when optional binding fails
    }

更新: 作者预期会有错误

URL初始化程序在无法解析给定字符串的情况下不会引发错误

如果字符串不表示有效字符串,则此初始化方法返回nil 网址。例如,一个空字符串或一个包含以下字符的字符 URL中的非法内容会产生nil。 source

,

您可以使用以下字符串创建网址:

let newString = "http://somehost:1337/parse/classes/CompEntry"
if let url = URL(string: newString) {
     print("here")
}

然后创建一个params字典,如:

 params = ["CompID": ["__type": "Pointer","className": "Competition","objectId": "CXy40U65Z9"]]

然后将这些参数发送到URLRequest的httpBody中。