Ryo
Ryo

Reputation: 93

How to find a string in a string for filtering data in Swift 3

I would like to know how to detect a String inside a String from stored data. All data is saved with UUID().uuidString. String data is saved in UITableView with its title String.

For example, if now I am in a DogTableView with its title in the navigation, "Dog", then the data is going to be "Dog". The data is "Dog" + uuid. And if now I move to a CatTableView with its title in the navigation, "Cat", then the data is going to be "Cat" + uuid.

Now we have two types of data, Dog + uuid and Cat + uuid.

So the problem is that I would like to extract only Dog + uuid data, by some algorithm. My attempt was in the following;

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if(segue.identifier == "animals"){

        let cell = sender as? UITableViewCell
        let indexPath = tableView.indexPath(for: cell!)

        let item:Animal
        item = self.animals[indexPath!.row]

        let dvc = segue.destination as! AnimalTableViewController
        dvc.topTItle = item.name!

        let singleton = AnimalManager.sharedInstance
        //Animal data is saved with CoreData in AnimalTableViewController
        let data = singleton.getAnimalData()

        for d in data {
            // This is not working..
            if (d.uuid?.contains(item.name!))! {
                dvc.displayArray.append(d)
            }
        }
        // I thought this would work by counting the item length 
        // Then using `Range` or something to detect the Dog or Cat. 
        // But I do not know how to do....at all
        let length = item.name!.characters.count
        for i in 0...length - 1 {

        }


    }
}

How am I able to filter data and show the filtered data into the next AnimaltableViewController appropriately?

Upvotes: 1

Views: 625

Answers (1)

vadian
vadian

Reputation: 285150

First of all, why for heaven's sake is uuid and name optional ?? I'm not aware of any animal without a name. And any nil value in uuid defeats the u representing unique.

Actually you can use the filter function to filter the items in one line.

dvc.displayArray = data.filter { $0.uuid.hasPrefix("Dog") && $0.uuid.contains(item.name) }

PS: However as you're dealing with Core Data it would be much more efficient to filter the data directly in Core Data.

Upvotes: 1

Related Questions