在这个 stackoverflow question中,建议将类型[AnyObject]
转换为类型化数组,但在我的情况下,返回值是单数AnyObject
向下转换为单数JSONObjectWithData
:
// ObjC def: public class func JSONObjectWithData(data: NSData, options opt: NSJSONReadingOptions) throws -> AnyObject
if let jsonResult = try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary {
if let results = jsonResult!["results"] as? NSArray { // ! needed or compile error
}
}
如何让 Swift 自动解包jsonResult
?
更新:这是一个更好的例子来说明问题:
func intOrThrow(arg: Int) throws -> AnyObject? {
if arg < 0 {
throw NSError(domain: "test", code: 400, userInfo: nil)
} else if arg == 0 {
return ["ZERO"]
} else if arg > 1000 {
return nil
}
return arg * 2
}
func strOrNil(arg: Int) -> String? {
if arg < 0 || arg > 1000 {
return nil
}
return "NUMBER\(arg)"
}
print("before intOrThrow(100) and optional unwrap")
if let x = try? self.intOrThrow(100) as? [String], // incorrect type
results = x?.count {
print("count is \(results). x is \(x)")
}
print("before intOrThrow(0) and optional unwrap")
if let x = try? self.intOrThrow(0) as? [String], // good type
results = x?.count {
print("count is \(results). x is \(x)")
}
print("before intOrThrow(-100) and optional unwrap")
if let x = try? self.intOrThrow(-100) as? [String], // throw
results = x?.count {
print("count is \(results). x is \(x)")
}
print("before intOrThrow(1111) and optional unwrap")
if let x = try? self.intOrThrow(1111) as? [String], // nil
results = x?.count {
print("count is \(results). x is \(x)")
}
print("before intOrThrow(200) and block")
if let x = try? self.intOrThrow(200) as? [String] { // incorrect type
print("count is \(x?.count). x is \(x)") // still require ! or ?, else compile error
}
print("before intOrThrow(0) and block")
if let x = try? self.intOrThrow(0) as? [String] { // good type
print("count is \(x?.count). x is \(x)") // still require ! or ?, else compile error
}
print("before intOrThrow(-200) and block")
if let x = try? self.intOrThrow(-200) as? [String] { // throw
print("count is \(x!.count). x is \(x)") // still require ! or ?, else compile error
}
print("before intOrThrow(2222) and block")
if let x = try? self.intOrThrow(2222) as? [String] { // nil
print("count is \(x?.count). x is \(x)") // still require ! or ?, else compile error
}
print("done intOrThrow")
print("before strOrNil(3333) and block")
if let x = self.strOrNil(2222) { // nil, no type cast
print("count is \(x.lowercaseString). x is \(x)") // don't require ! or ?
}
print("done strOrNil")
输出: 在 intOrThrow(100) 和可选展开之前 在 intOrThrow(0) 和可选展开之前 计数为 1。x 是可选的(["ZERO"]) 在 intOrThrow(-100) 和可选展开之前 在 intOrThrow(1111) 和可选展开之前 在 intOrThrow(200) 之前并阻止 计数为零。x 为零 在 intOrThrow(0) 之前并阻塞 计数是可选的(1)。x 是可选的([“零”]) 在 intOrThrow(-200) 之前并阻止 在 intOrThrow(2222) 之前并阻止 计数为零。x 为零 完成 inOrThrow 在 strOrNil(3333) 和块之前 完成 strOrNil