无法在swift中将逗号分隔的字符串转换为整型数组



我得到一个整型字符串,我需要在数组中转换,如果是整型

我需要这样做[8,9,10]

let stringOfints = "8,9,10"
let arrOfIds = stringOfints?.components(separatedBy: ",")

0/p:

["8","9","10"]

编辑:这里我需要检查id与字符串的int

my json like this

{
"jsonrpc": "2.0",
"result": {
"sub_category": [
{
"id": 2,
"title": "Logo Design"
},
{
"id": 3,
"title": "banner design"
},
{
"id": 5,
"title": "business web site"
},
{
"id": 10,
"title": "Business Card Design"
}
]
}
}

代码:这里arrOfIds是[2,3],但当我比较arrOfIds与jsonid,如果它匹配,然后追加其标题到arrSubCat,但如果我打印arrSubCat在循环结束,那么为什么所有标题都来了…请帮助

var arrSubCat:[String] = []
private func getSubCategoryServiceIDs() {
let param = ["category_id" : categoryID!]
APIReqeustManager.sharedInstance.serviceCall(param: param, url: CommonUrl.get_sub_category) { [weak self] (resp) in
self?.getSubCategoryIDs = GetSubCatModel(dictionary: resp.dict as NSDictionary? ?? NSDictionary())

if self?.getServiceDetails?.result?.serviceDetails?.sub_cat_group != nil{
let kat = self?.getSubCategoryIDs?.result?.sub_category ?? []
let value = self?.getServiceDetails?.result?.serviceDetails?.sub_cat_group
let arrOfIds = value?.components(separatedBy: ",").compactMap { Int($0) }

for singleCat in kat{
if ((arrOfIds?.contains(singleCat.id ?? 0)) != nil){
self?.arrSubCat.append(singleCat.title ?? "")
}
}
print("array of sub cat (self?.arrSubCat)")//getting all titles why?
self?.collectionView.reloadData()
}
}
}

o/p

子目录数组(["标志设计"横幅设计"商业网站";名片设计"])

之前回答

您必须将String转换为Int

let stringOfints = "8,9,10"
let arrOfIds = stringOfints.components(separatedBy: ",").compactMap { Int($0) }

更新答案

修改API调用中的代码,如下所示并尝试。

let arrOfIds = value?.components(separatedBy: ",").compactMap { Int($0) } ?? []

for singleCat in kat {
if arrOfIds.contains(singleCat.id ?? 0) {
self?.arrSubCat.append(singleCat.title ?? "")
}
}

最新更新