I'm guessing you mean that you want to retrieve the index without manually searching the array with, say, a for-in
loop.
In Swift 4 you can use Array.index(where:)
in combination with the StringProtocol
's generic contains(_:)
function to find what you're looking for.
Let's imagine you're looking for the first line containing the text "important stuff" in your text: [String]
array.
You could use:
text.index(where: { $0.contains("important stuff") })
Behind the scenes, Swift is looping to find the text, but with built-in enhancements, this should perform better than manually looping through the text
array.
Note that the result of this search could be nil
if no matching lines are present. Therefore, you'll need to ensure it's not nil
before using the result:
Force unwrap the result (risking the dreaded fatal error: unexpectedly found nil while unwrapping an Optional value
):
print(text[lineIndex!)
Or, use an if let
statement:
if let lineIndex = stringArray.index(where: { $0.contains("important stuff") }) {
print(text[lineIndex])
}
else {
print("Sorry; didn't find any 'important stuff' in the array.")
}
Or, use a guard
statement:
guard let lineIndex = text.index(where: {$0.contains("important stuff")}) else {
print("Sorry; didn't find any 'important stuff' in the array.")
return
}
print(text[lineIndex])