在 xcode 8 Swift 3 中键入“Any"没有下标成员 [英] Type 'Any' Has no Subscript Members in xcode 8 Swift 3
问题描述
我的应用程序应该去特定位置下拉它需要加载的网站.在 2.3 中它就像一个魅力,但自从我更新了 xcode(我没有很多经验)它给了我错误类型'Any'没有下标成员"并突出显示json"就在第三行之前
My App is supposed to go to a specific location to pull down the website it needs to load. In 2.3 it worked like a charm, but since I've updated xcode (which I don't have a ton of experience in) it is giving me the error "type 'Any' has no subscript members" and highlighting the "json" right before line three
...Retriever = json["WEB"]...
这是与之相关的代码.
let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments)
if let Retriever = json["WEB"] as? [[String: AnyObject]] {
for website in Retriever {
if let name = website["URL"] as? String {
self.loadAddressURL(name)
我觉得我错过了一些小事.如果有更好的方法来做到这一点,我希望得到建议.URL 返回此 JSON
I feel like I am missing something small. If there is a better way to do this, I would love suggestions. The URL returns this JSON
{
"WEB" : [
{
"URL" : "http://www.google.com"
}
]
}
但是如果我可以将其简化为只是,我会喜欢它
but I would love it if I could simplify it to just
{"URL":"http://www.google.com"}
推荐答案
试试这个:
let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String:AnyObject]
安全方式:
do {
if let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as? [String:Any] {
print(json)
}
} catch let err{
print(err.localizedDescription)
}
您必须将类型 Any
转换为 Swift 字典类型 [String:AnyObject]
.
You have to cast type Any
to Swift dictionary type [String:AnyObject]
.
Swift 3
在 swift 3 中 AnyObject
的目的更加明确.所以更有利的 Swift 字典类型将是 [String:Any]
.
Swift 3
In swift 3 the purpose of AnyObject
is more clarified. So more favourable Swift Dictionary type will be [String:Any]
.
Any
是任何数据类型的别名.AnyObject
是从类派生的任何数据类型的别名.
Any
is an alias for any data type.
AnyObject
is an alias for any data type derived from a class.
欲了解更多信息,请访问:https://craiggrummitt.com/2016/09/16/any-vs-anyobject-vs-nsobject-in-swift-3/
For more info visit: https://craiggrummitt.com/2016/09/16/any-vs-anyobject-vs-nsobject-in-swift-3/
这篇关于在 xcode 8 Swift 3 中键入“Any"没有下标成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!