如何将整数数组转换为逗号分隔的字符串(在Swift中)

12 浏览
0 Comments

如何将整数数组转换为逗号分隔的字符串(在Swift中)

在我的应用程序中,我使用了一个对象,假设为var selectedIds = Int。我希望这个selectedIds以逗号分隔。因为我需要将selectedIds发送到下一个屏幕,在这个屏幕上调用API时需要使用逗号分隔的参数。我希望得到的ids是556,573,这样我就可以将其传递给接收控制器的参数中。

我想在以下的viewcontroller文件中发送selectedIds数组:

class CategoryViewController: UIViewController {

//MARK: IBOutlets

@IBOutlet weak var store_bar: UIViewX!

@IBOutlet weak var store_title: UIButton!

@IBOutlet weak var category_title: UIButton!

@IBOutlet weak var category_bar: UIViewX!

@IBOutlet weak var categoryColView: UICollectionView!

var selectedBtnIndex:Int = 1

var selectedIds = [Int]()

var storeIds = [Int]()

var categoryData = [ModelCategories]()

var storeData = [ModelStore]()

var arrCategoryImages = [UIImage]()

override func viewDidLoad() {

super.viewDidLoad()

// 注册collectionview cell

self.categoryColView.register(UINib(nibName: "CategoryCell1", bundle: nil), forCellWithReuseIdentifier: "CategoryCell1")

self.categoryColView.register(UINib(nibName: "StoresCell", bundle: nil), forCellWithReuseIdentifier: "StoresCell")

self.store_bar.isHidden = true

self.getCategoriesList()

self.getStoreList()

}

override var preferredStatusBarStyle: UIStatusBarStyle {

return .lightContent

}

@objc func click_Category(sender: UIButton!) {

if sender.isSelected == true {

selectedIds.append(categoryData[sender.tag].ID!)

sender.setImage(#imageLiteral(resourceName: "image_checked"), for: .normal)

sender.isSelected = false

}else {

selectedIds = selectedIds.filter{ $0 != sender.tag }

sender.setImage(#imageLiteral(resourceName: "image_unchecked"), for: .normal)

sender.isSelected = true

}

}

@objc func click_store(sender: UIButton!) {

if sender.isSelected == true {

selectedIds.append(storeData[sender.tag].ID!)

sender.setImage(#imageLiteral(resourceName: "image_checked"), for: .normal)

sender.isSelected = false

}else {

selectedIds = selectedIds.filter{ $0 != sender.tag }

sender.setImage(#imageLiteral(resourceName: "image_unchecked"), for: .normal)

sender.isSelected = true

}

}

//MARK: IBActions

@IBAction func categoriesData(_ sender: UIButton) {

selectedBtnIndex = 1

self.categoryColView.isHidden = false

self.store_bar.isHidden = true

self.category_title.setTitleColor(UIColor.black, for: .normal)

self.category_bar.isHidden = false

self.store_title.setTitleColor(UIColor(rgb: 0xAAAAAA), for: .normal)

self.categoryColView.reloadData()

}

@IBAction func storeData(_ sender: UIButton) {

selectedBtnIndex = 2

self.categoryColView.isHidden = false

self.store_bar.isHidden = false

self.store_title.setTitleColor(UIColor.black, for: .normal)

self.category_bar.isHidden = true

self.category_title.setTitleColor(UIColor(rgb: 0xAAAAAA), for: .normal)

self.categoryColView.reloadData()

}

@IBAction func showHomeScreen(_ sender: UIButton) {

let vc = self.storyboard?.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController

if selectedBtnIndex == 1 {

vc.selectedIds = self.selectedIds

// vc.couponId = categoryData[sender.tag].ID!

}else {

vc.selectedIds = self.selectedIds

}

self.navigationController?.pushViewController(vc, animated:true)

}

@IBAction func toSearchPage(_ sender: UIButton) {

let vc = self.storyboard?.instantiateViewController(withIdentifier: "SearchPageController") as! SearchPageController

self.navigationController?.pushViewController(vc, animated:true)

}

func getCategoriesList() {

if ApiUtillity.sharedInstance.isReachable() {

ApiUtillity.sharedInstance.StartProgress(view: self.view)

APIClient().API_GET(Url: SD_GET_CategoriesList, Params: [:], Authentication: true, Progress: true, Alert: true, Offline: false, SuperVC: self, completionSuccess: { (modelResponse) in

ApiUtillity.sharedInstance.StopProgress(view: self.view)

if(modelResponse.success == true) {

self.categoryData.removeAll()

let resul_array_tmp_new = modelResponse.categories! as NSArray

if resul_array_tmp_new.count > 0 {

for i in modelResponse.categories! {

if i.count != 0 {

if let image = UIImage(named: "\(i.slug!.uppercased())") {

self.arrCategoryImages.append(image)

self.categoryData.append(i)

}else {

self.arrCategoryImages.append(UIImage(named: "tickets")!)

self.categoryData.append(i)

}

}

}

}

}

else {

self.view.makeToast(modelResponse.message)

}

ApiUtillity.sharedInstance.StopProgress(view: self.view)

self.categoryColView.reloadData()

}) { (failed) in

ApiUtillity.sharedInstance.StopProgress(view: self.view)

self.view.makeToast(failed.localizedDescription)

}

}

else

{

self.view.makeToast("No Internet Connection..")

}

}

func getStoreList() {

if ApiUtillity.sharedInstance.isReachable() {

ApiUtillity.sharedInstance.StartProgress(view: self.view)

APIClient().API_GET(Url: SD_GET_StoreList, Params: [:], Authentication: true, Progress: true, Alert: true, Offline: false, SuperVC: self, completionSuccess: { (modelResponse) in

ApiUtillity.sharedInstance.StopProgress(view: self.view)

if(modelResponse.success == true) {

self.storeData.removeAll()

let resul_array_tmp_new = modelResponse.store! as NSArray

if resul_array_tmp_new.count > 0 {

for i in modelResponse.store! {

if i.count != 0 {

self.storeData.append(i)

}

}

}

}

else {

self.view.makeToast(modelResponse.message)

}

ApiUtillity.sharedInstance.StopProgress(view: self.view)

self.categoryColView.reloadData()

}) { (failed) in

ApiUtillity.sharedInstance.StopProgress(view: self.view)

self.view.makeToast(failed.localizedDescription)

}

}

else

{

self.view.makeToast("No Internet Connection..")

}

}

}

//MARK: Delegate and Data Source Methods

extension CategoryViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

if selectedBtnIndex == 1{

return categoryData.count

}else {

return storeData.count

}

}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

if selectedBtnIndex == 1{

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CategoryCell1", for: indexPath) as! CategoryCell1

let dict = categoryData[indexPath.row]

if let catName = dict.name, catName.count != 0 {

cell.categoryName.text = catName

}

if let catOffersCount = dict.count {

if catOffersCount == 1 {

cell.catOfferCount.text = "\(catOffersCount)"+" "+"Offer"

}else {

cell.catOfferCount.text = "\(catOffersCount)"+" "+"Offers"

}

}

cell.categoryImage.image = arrCategoryImages[indexPath.row]

cell.btn_click.tag = indexPath.row

cell.btn_click.addTarget(self, action: #selector(self.click_Category), for: .touchUpInside)

if selectedIds.contains(categoryData[indexPath.row].ID!) {

cell.btn_click.setImage(#imageLiteral(resourceName: "image_checked"), for: .normal)

cell.btn_click.isSelected = true

}else {

cell.btn_click.setImage(#imageLiteral(resourceName: "image_unchecked"), for: .normal)

cell.btn_click.isSelected = false

}

return cell

}else {

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "StoresCell", for: indexPath) as! StoresCell

let dict = storeData[indexPath.row]

if let storeName = dict.name, storeName.count != 0 {

cell.storeName.text = storeName

}

if let storeOfferCount = dict.count {

cell.storeOfferCount.text = "\(storeOfferCount)"+" "+"Offers"

}

cell.store_btn_click.tag = indexPath.row

cell.store_btn_click.addTarget(self, action: #selector(self.click_store), for: .touchUpInside)

if selectedIds.contains(storeData[indexPath.row].ID!) {

cell.store_btn_click.setImage(#imageLiteral(resourceName: "image_checked"), for: .normal)

cell.store_btn_click.isSelected = true

}else {

cell.store_btn_click.setImage(#imageLiteral(resourceName: "image_unchecked"), for: .normal)

cell.store_btn_click.isSelected = false

}

return cell

}

}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

if selectedBtnIndex == 1{

return CGSize(width: (UIScreen.main.bounds.width) / 3, height: 93)

}else {

return CGSize(width: (UIScreen.main.bounds.width) / 2, height: 48)

}

}

我想在以下的viewcontroller文件中使用selectedIds数组:

class HomeViewController: UIViewController {

var couponsData = [ModelCoupons]()

var couponId = Int()

var selectedIds = [Int]()

@IBOutlet weak var homeTblView: UITableView!

override func viewDidLoad() {

super.viewDidLoad()

self.homeTblView.register(UINib(nibName: "HomeCell", bundle: nil), forCellReuseIdentifier: "HomeCell")

self.post_CouponsData()

print(selectedIds)

}

override var preferredStatusBarStyle: UIStatusBarStyle {

return .lightContent

}

//MARK: IBActions

@IBAction func toCategoryScreen(_ sender: UIButton) {

self.navigationController?.popViewController(animated: true)

}

@IBAction func toSearchPage(_ sender: UIButtonX) {

let vc = self.storyboard?.instantiateViewController(withIdentifier: "SearchPageController") as! SearchPageController

self.navigationController?.pushViewController(vc, animated: true)

}

func post_CouponsData() {

if ApiUtillity.sharedInstance.isReachable() {

var params = [String : String]()

params ["term_ids"] = "\(self.selectedIds)"

ApiUtillity.sharedInstance.StartProgress(view: self.view)

APIClient().API_POST(Url: SD_POST_CouponsList, Params: params as [String:AnyObject], Authentication: true, Progress: true, Alert: true, Offline: false, SuperVC: self, completionSuccess: { (modelResponse) in

ApiUtillity.sharedInstance.StopProgress(view: self.view)

if(modelResponse.success == true) {

ApiUtillity.sharedInstance.StopProgress(view: self.view)

let dict = modelResponse.coupons

for i in dict! {

self.couponsData.append(i)

}

}else {

self.view.makeToast(modelResponse.message)

}

ApiUtillity.sharedInstance.StopProgress(view: self.view)

self.homeTblView.reloadData()

}) { (failed) in

self.view.makeToast(failed.localizedDescription)

ApiUtillity.sharedInstance.StopProgress(view: self.view)

}

}else {

self.view.makeToast("No internet connection...")

ApiUtillity.sharedInstance.StopProgress(view: self.view)

}

}

}

extension HomeViewController: UITableViewDelegate, UITableViewDataSource {

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

return couponsData.count

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCell(withIdentifier: "HomeCell", for: indexPath) as! HomeCell

let dict = couponsData[indexPath.row]

if let postTitle = dict.postTitle, postTitle.count != 0 {

cell.ticket_postTitle.text = postTitle

}

if let postContent = dict.postContent, postContent.count != 0 {

cell.ticket_postContent.text = postContent

}

if let storeName = dict.stores, storeName.count != 0 {

cell.storename.text = storeName

}

let dateFormatterGet = DateFormatter()

dateFormatterGet.dateFormat = "yyyy-MM-dd"

let dateFormatterPrint = DateFormatter()

dateFormatterPrint.dateFormat = "dd MMMM yyyy"

let datee = ApiUtillity.sharedInstance.ConvertStingTodate(forApp: dict.validTill!)

cell.ticket_ValidDate.text = dateFormatterPrint.string(from: datee)

cell.ticketImageView.tintColor = .random()

return cell

}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

return 339.0

}

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {

return 339.0

}

}

0
0 Comments

将一个整数数组转换为逗号分隔的字符串,需要将整数数组映射为字符串数组,然后使用逗号作为分隔符将数组连接起来。

解决方法如下:

params["term_ids"] = self.selectedIds.map(String.init).joined(separator: ",")

以上代码中,`self.selectedIds` 是一个整数数组,通过 `map` 方法将其转换为字符串数组,然后使用 `joined(separator: ",")` 方法将字符串数组连接成一个逗号分隔的字符串。

这样就可以将整数数组转换为逗号分隔的字符串了。

0
0 Comments

在Swift中,将整数数组转换为逗号分隔的字符串是一个常见的需求。解决这个问题的方法如下:

首先,我们可以使用map函数将整数数组转换为字符串数组。在这个例子中,我们假设整数数组的名称是selectedIds

selectedIds.map(String.init)

这将使用String.init将每个整数转换为字符串,并返回一个新的字符串数组。

接下来,我们可以使用joined(separator:)函数将字符串数组连接成一个单独的字符串。在这个例子中,我们将使用逗号作为分隔符。

selectedIds.map(String.init).joined(separator: ",")

这个表达式将返回一个逗号分隔的字符串,其中包含了整数数组中的所有元素。

通过以上的方法,我们可以很方便地将整数数组转换为逗号分隔的字符串。无论是在处理用户输入、生成日志信息还是其他类似的场景中,这个技巧都非常有用。

0