Get Searched Part of String in Swift


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


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


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


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.


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.


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.


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. 👍




I am a professional software engineer.

Love podcasts or audiobooks? Learn on the go with our new app.

Beginning an iOS Journey

Handling Colors in SwiftUI

How to Use Codable in Firebase Realtime Database

Dynamic Linker Not Working in Big Sur

Attention Apple Users….

NSBrazil as a knowledge boost

The Foundations of Unit Testing (3/3): Effectively testing the MVC pattern in Swift

Arlo Firmware Update |

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store


I am a professional software engineer.

More from Medium

Getting your code crashed inside a Swift loop

The Structure of a Swift Package

Swift : Understanding Mutating Functions in One Minute

iOS testing — 4 crossroads technique — Part 2