Updated 30 August 2022
Hello guy, Today we will learn about Array list Rearrangement in swift.
Sometimes we need to change the position of the array like I want to change the array index 6 value to index 2 and remain list is the same as per their position. At that time we need to do array rearrangement. let’s start with an example.
Step1:- Firstly, Create an Xcode project
File –> New –> Project –> iOS –> Next and add your project name then create.
Step 2:- Secondly, Create a table view in the storyboard.
Step 3:- Now, Create a swift class and add the code and run the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
import UIKit class ViewController: UIViewController { @IBOutlet weak var listTableView: UITableView! var arrayList:[String] = ["one", "Two", "Three", "Four","Five", "Six","Seven", "Eight", "Nine", "Ten"] override func viewDidLoad() { super.viewDidLoad() listTableView.delegate = self listTableView.dataSource = self listTableView.reloadData() // Do any additional setup after loading the view. } } extension ViewController : UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return arrayList.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCell(withIdentifier: "ListTableViewCell") as? ListTableViewCell { cell.valueLabel.text = arrayList[indexPath.row] return cell } return UITableViewCell() } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 50 } } |
And the output is –
Step 4:- Now, I want to change the position of the array list. In my example I want to change the number nine position at index 2, For this, I need to call a function.
1 2 3 4 5 6 7 8 |
func arrayRearrange<T>(array: Array<T>, fromIndex: Int, toIndex: Int) -> Array<T>{ var arrayValue = array let element = arrayValue.remove(at: fromIndex) arrayValue.insert(element, at: toIndex) return arrayValue } |
Step 5:- Function calling to change the position. you just need to call
1 |
arrayList = arrayRearrange(array: arrayList, fromIndex: 8, toIndex: 2) |
Step 6:- Lastly, Run the project and see the result!!!
In this screenshot, you will see that number nine is shifted to position 2, and the remaining array is the same.
In this blog, we have discussed Array list Rearrangement in swift.
I hope this blog will help you to understand the rearrangement process of the array.
To learn about more iOS-related topics, Please click here.
Thanks for reading!!!
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.