【问题标题】:Xcode: Get dictionary key from URL not workingXcode:从 URL 获取字典键不起作用
【发布时间】:2020-06-22 08:19:19
【问题描述】:

我正在使用最新版本的XcodeSwift

我有以下代码来获取WKWebView 的当前 URL:

let htmlURL = navigationAction.request.url!.absoluteURL
print(htmlURL)

print 函数输出如下:https://www.example.com/

现在,我有以下代码:

if let htmlSourceCode = dict[htmlURL] {
    print(htmlSourceCode)
} else {
    print("key not found")
}

出于某种原因,这给了我:key not found

但是当像这样直接使用https://www.example.com/ 而不是htmlURL 时:

if let htmlSourceCode = dict["https://www.example.com/"] {
    print(htmlSourceCode)
} else {
    print("key not found")
}

它正在按预期工作并在控制台中向我显示源代码。

为什么它可以与dict["https://www.example.com/"] 一起使用,但不能与dict[htmlURL] 一起使用,尽管在这两种情况下都是完全相同的字符串?

编辑:

dict 如下:

if let path = Bundle.main.path(forResource: "html", ofType: "plist") {
let dictRoot = NSDictionary(contentsOfFile: path)
if let dict = dictRoot {
}

【问题讨论】:

  • 什么是dict?请添加。
  • 这意味着您正在验证您的 dict 作为 key ,您使用 dict 的值进行验证,在此处添加您的 dict
  • dict 得到了什么?将其打印并粘贴到此处,以便我们查看其中存在哪些值。

标签: ios swift xcode dictionary


【解决方案1】:

使用URLabsoluteString 作为dict 的密钥。试试这个:

if let htmlSourceCode = dict[htmlURL.absoluteString] {
    print(htmlSourceCode)
} else {
    print("key not found")
}

【讨论】:

  • 不客气。您应该添加有问题的dict 声明。我犯了一个类似的错误,所以我可以识别你的问题。
猜你喜欢
  • 1970-01-01
  • 2022-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多