Replace or Remove a String in your Array


Working on a project today, I ran into a solution that would be good to share with IOS Developers. That is using a swift tool .firstIndex(of: String) to find or replace an indexed string in your array. In my case this was used for error handling!

I have an array setup called var testSlice: [String] = [] which is the final form of var items: [String] = []. The items array is holding strings that represent profilePic id’s that get used in a method later on in the class file.

Empty strings "" were in the array as placeholder values, that needed removed before the array passed its data to a UICollectionView .

Here is my solution using .firstIndex(of: String) :

if let index = self.testSlice.firstIndex(of: "") {self.testSlice.remove(at: index)collectionView.reloadData()}

In the first line we are checking for items that contain an empty string at their index and storing it in a variable. The index found then gets passed to the .remove function as an int .. removing it from our testSlice array.

After thats done the collectionView data gets reloaded. Attached is a picture of the UI as an example to show whats possible. I hope this helped, and served its purpose as an easy solution!

therisecollection.co

therisecollection

Innovating without forgetting to be creative.

Joshua Paulsen

Written by

Published App Developer, Founder of The Rise Collection.

therisecollection

Innovating without forgetting to be creative.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade