我想知道为什么AnyObject
Swift 2.2(Xcode 7.3)
突然显示错误并且显示错误" 模糊地使用'下标' "。
以下是我以前工作正常的代码:
func sampleMethod() {
PFCloud.callFunctionInBackground("sampleFunction", withParameters: nil) { (response, error) -> Void in
guard let response = response else {
if let error = error {
print(error)
}
return
}
if let records = response as? [AnyObject] { // Valid response
for record in records {
if let activeCount = record["activeCount"] as? Int {
print("activeCount: \(activeCount)")
}
if let persons = record["persons"] as? [AnyObject] {
for person in persons {
if let age = person["age"] as? Int {
print("age: \(age)")
}
if let properties = person["properties"] as? [AnyObject] {
for property in properties {
if let propertyName = property["name"] as? String {
print("propertyName: \(propertyName)")
}
if let propertyValue = property["value"] as? String {
print("propertyValue: \(propertyValue)")
}
}
}
}
}
}
} else {
print("Invalid response")
}
}
}
在我将Swift 2.2
更改为AnyObject
之后,我的代码现在正在[String: AnyObject]
中运行:
func sampleMethod() {
PFCloud.callFunctionInBackground("sampleFunction", withParameters: nil) { (response, error) -> Void in
guard let response = response else {
if let error = error {
print(error)
}
return
}
if let records = response as? [[String: AnyObject]] { // Valid response
for record in records {
if let activeCount = record["activeCount"] as? Int {
print("activeCount: \(activeCount)")
}
if let persons = record["persons"] as? [[String: AnyObject]] {
for person in persons {
if let age = person["age"] as? Int {
print("age: \(age)")
}
if let properties = person["properties"] as? [[String: AnyObject]] {
for property in properties {
if let propertyName = property["name"] as? String {
print("propertyName: \(propertyName)")
}
if let propertyValue = property["value"] as? String {
print("propertyValue: \(propertyValue)")
}
}
}
}
}
}
} else {
print("Invalid response")
}
}
}
以下是我将AnyObject
更改为[String: AnyObject]
时解决的一系列错误的屏幕截图:
在Swift 2.2中AnyObject
上不允许有关为什么下标的想法?
答案 0 :(得分:1)
首先,我无法重现这个问题。这在Xcode 7.3(Swift 2.2)中编译并运行正常:
var records = [AnyObject]()
records.append(["howdy":"hello"])
for record in records {
if let x = record["howdy"] {
print(x)
}
}
因此,我不得不猜测您所看到的问题是由您正在使用的某些库引入的,例如Parse。其中大多数都有其他定义(可能是objectForKeyedSubscript:
)的定义。
但其次,你应该从来没有这样做过。 Swift就是严格打字。订阅AnyObject是愚蠢的,就像向AnyObject发送任何消息一样。即使你可以逃脱它,你也不应该这样做。有明智的方法可以确保你获得的是一本字典并在你下标之前输入一个字典。使用它们。