In Objective-C
the code to check for a substring in an NSString
is:
NSString *string = @"hello Swift";
NSRange textRange =[string rangeOfString:@"Swift"];
if(textRange.location != NSNotFound)
{
NSLog(@"exists");
}
But how do I do this in Swift?
Best Answer
You can do exactly the same call with Swift:
Swift 4 & Swift 5
In Swift 4 String is a collection of
Character
values, it wasn't like this in Swift 2 and 3, so you can use this more concise code1:Swift 3.0+
Older Swift
I hope this is a helpful solution since some people, including me, encountered some strange problems by calling
containsString()
.1PS. Don't forget to
import Foundation
Footnotes