Get Searched Part of String in Swift

M.Abbas
2 min readMay 5, 2021

Step-1

First, create a simple playground file from Xcode like the below screenshots.

Step-2

Import the Foundation at the type and then start typing the next code.

Step-3

Now create a text var and put some text into that var

Step-4

Create a function getHighlightedString function which will get two String parameters and will return the String. One parameter is original text and the other is searchText which we will search into the origonalText.

Step-5

After that use the if-else condition into that function. If the searchText is in the range of the orignalText then if condition will run otherwise else condition will run, and in else condition simply originalText return.

Step-6

After that use the String distance which will return the distance between two indices. Now if that index or you can say distance is greater than 30 then it means the string does not occur at the start. Remember that the index we get from the distance method is the start index of searchText. Now I want to add 20 characters before the index. So minus 20 into the index. Now convert the originalText into Array and the get character index to originalText count and convert the Array into the String. This will return the String where the searchText will occur.

Step-7

After that call the getHighlightedString function.

Now you can see the output which has the searchText. 💁‍♂️

Complete Code

Hope you understand if you have any issue then a comment. 👍

Patreon

--

--