Home > Mobile >  unable to convert coma seperated string to array of ints in swift
unable to convert coma seperated string to array of ints in swift

Time:05-13

I am getting string of ints, i need to convert that in array if ints

i need like this [8,9,10]

  let stringOfints = "8,9,10"

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

0/p:

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

EDIT: here i need to check id with string of ints

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"
        }
    ]
}
}

code: here arrOfIds are [2, 3] but when i compare arrOfIds with json id and if its match then appending its title to arrSubCat but if i print arrSubCat at end of for loop then why all titels are coming...plz help

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

array of sub cat (["Logo Design", "banner design", "business web site", "Business Card Design"])

CodePudding user response:

Previous Answer

You have to convert the String to Int

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

Updated Answer

Modify the code inside API call like below and try.

let arrOfIds = value?.components(separatedBy: ",").compactMap { Int($0) } ?? []
        
for singleCat in kat {
    if arrOfIds.contains(singleCat.id ?? 0) {
        self?.arrSubCat.append(singleCat.title ?? "")
    }
}
  • Related