arraysswiftfilter

Filter for part of a string in an array


Cannot figure out how to filter [BookFromMatching] to return only values from bisacName.iBooks.bisacsubjects where the array of strings contains "Romance". bisacName.iBooks.bisacsubjects is an array of strings that contains values like ["Fiction | Romance | Fantasy", "Fiction | Crime | True Crime", "xxx | xxx | xxx"]. The below code will find no records by searching for "Romance" because it only looks for a match on the entire string in the array, not just part of the string. Changing the below code to "Fiction | Romance | Fantasy" will find records but I want to search for part of a string in this array

var filteredOptions: [BookFromMatchingData] {
    return shuffleEm.filter { bisacName in
        bisacName.iBooks.bisacsubjects!.caseInsensitiveContains("Romance")
    }
}

Solution

  • You want to use localizedCaseInsensitiveContains on each string element in the array

    bisacsubjects.contains(where: { $0.localizedCaseInsensitiveContains("Romance") })