gpt4 book ai didi

ios - 根据值更改 Swift 中语句的类型

转载 作者:搜寻专家 更新时间:2023-11-01 06:32:35 24 4
gpt4 key购买 nike

我收到一个 Json get 请求,我的值是一个数组,因此为什么我将我的 JSONSerializaion 设置为? NSArray.

但是,有时在我的后端,值不是作为数组而是作为字典发送的,所以我如何检查我的值的类型并相应地更改 as?,如果这样的话感觉

do{
let json = try
JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSArray //This is what I want to change

有时值作为字典发送,那么我如何才能让我的应用程序知道执行 as? NSDictionary 而不是 as? NS数组

最佳答案

我可能会使用 switch 来区分可能性:

do {
switch try JSONSerialization.jsonObject(with: arrayJson, options: .mutableContainers) {
case let array as NSArray:
// Use array here. For example:
print("got an array of \(array.count) elements")

case let dictionary as NSDictionary:
// Use dictionary here. For example:
print("got a dictionary with keys: \(dictionary.allKeys)")

case let other:
print("I got something I didn't understand: \(other)")
}
} catch {
print(error)
}

如果你愿意,你可以使用多个 if let 分支:

do {
let object = try JSONSerialization.jsonObject(with: arrayJson, options: .mutableContainers)
if let array = object as? NSArray {
print("got an array of \(array.count) elements")
} else if let dictionary = object as? NSDictionary {
print("got a dictionary with keys: \(dictionary.allKeys)")
}
} catch {
print(error)
}

关于ios - 根据值更改 Swift 中语句的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45179573/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com