【发布时间】:2022-01-20 12:18:21
【问题描述】:
这是 JSON 响应:
{
"result": {
"data": [
{
"id": 150,
"category": {
"title": "IT Professional",
},
"sub_category": {
"title": "Social media marketing",
}
},
{
"id": 166,
"category": {
"title": "Online Marketing",
},
"sub_category": {
"title": "Google Adwords",
}
},
......
]
}
}
我创建了这样的模型:使用 swift 类.. 因为我需要使用不可编码的 swift 类
public class AutoSearchResultModel {
public var result : AutoSearchResult?
}
public class AutoSearchResult {
public var data : Array<SearchData>?
}
public class SearchData {
public var id : Int?
public var category : Category?
public var sub_category : Sub_category?
}
public class Category {
public var title : String?
}
public class Sub_category {
public var title : String?
}
这里我需要显示category-> 标题和sub_category -> 标题一起显示在数组中,如下所示
为此,我的代码是:如何在 dropDownArray 中显示 category-> 标题和 sub_category-> 标题,一旦我得到 dropDownArray,我就可以在我的下拉,我可以显示..请指导我
class SearchResultVC: UIViewController{
var dropDown = DropDown()
var dropDownArray = [String]()
func autoSearchService(){
let parameters = [
"keyword" : searchTF.text
] as [String : Any]
APIReqeustManager.sharedInstance.serviceCall(param: parameters as [String : Any], method: .post, url: CommonUrl.auto_search, isTokenNeeded: true) { [weak self] (resp) in
self?.autosearchResult = AutoSearchResultModel(dictionary: resp.dict as NSDictionary? ?? NSDictionary())//response coming perfectly
let totData = autosearchResult?.result?.data
print("total data is: \(totData)")//up to array of data also coming
dropDownArray = (totData.category.title) + (totData.sub_category.title)
}
}
}
错误:
“[SearchData]?”类型的值没有成员“类别”
“[SearchData]?”类型的值没有成员“子类别”
【问题讨论】:
-
不是一个解决方案,但如果您将计算属性添加到 SearchData 并将类别和子类别作为字符串返回,它将使您的代码更清晰。为什么你的类中的所有属性都是可选的,这肯定不是你拥有的 json 数据的真实表示?需要时使用 optional,因为非可选属性在代码中更容易处理。
-
另外,如果您使用我的计算属性,您可以使用
map或compactMap快速从您的data数组中获取字符串数组 -
totData.map {$0.category.title + $0.sub_category.title}
标签: ios arrays json swift dictionary