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?
Sommaire |
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?
You can do exactly the same call with Swift:
Swift 3.0+
var string = "hello Swift" if string.range(of:"Swift") != nil{ println("exists") } // alternative: not case sensitive if string.lowercased().range(of:"swift") != nil { println("exists") }
Older Swift
var string = "hello Swift" if string.rangeOfString("Swift") != nil{ println("exists") } // alternative: not case sensitive if string.lowercaseString.rangeOfString("swift") != nil { println("exists") }
I hope this is a helpful solution since some people, including me, encountered some strange problems by calling containsString().
PS. Don t forget to import Foundation
License : cc by-sa 3.0
http://stackoverflow.com/questions/24034043/how-do-i-check-if-a-string-contains-another-string-in-swift