In Objective-C
the code to check for a substring in an NSString
is:
NSString *string = @\"hello Swift\";
NSRange textRange =[strin
You can do exactly the same call with Swift:
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:
let string = "hello Swift"
if string.contains("Swift") {
print("exists")
}
var string = "hello Swift"
if string.range(of:"Swift") != nil {
print("exists")
}
// alternative: not case sensitive
if string.lowercased().range(of:"swift") != nil {
print("exists")
}
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()
.1
PS. Don't forget to import Foundation
Here is my first stab at this in the swift playground. I extend String by providing two new functions (contains and containsIgnoreCase)
extension String {
func contains(other: String) -> Bool{
var start = startIndex
do{
var subString = self[Range(start: start++, end: endIndex)]
if subString.hasPrefix(other){
return true
}
}while start != endIndex
return false
}
func containsIgnoreCase(other: String) -> Bool{
var start = startIndex
do{
var subString = self[Range(start: start++, end: endIndex)].lowercaseString
if subString.hasPrefix(other.lowercaseString){
return true
}
}while start != endIndex
return false
}
}
Use it like this
var sentence = "This is a test sentence"
sentence.contains("this") //returns false
sentence.contains("This") //returns true
sentence.containsIgnoreCase("this") //returns true
"This is another test sentence".contains(" test ") //returns true
I'd welcome any feedback :)
Swift 4 way to check for substrings, including the necessary Foundation
(or UIKit
) framework import:
import Foundation // or UIKit
let str = "Oh Canada!"
str.contains("Can") // returns true
str.contains("can") // returns false
str.lowercased().contains("can") // case-insensitive, returns true
Unless Foundation
(or UIKit
) framework is imported, str.contains("Can")
will give a compiler error.
This answer is regurgitating manojlds's answer, which is completely correct. I have no idea why so many answers go through so much trouble to recreate Foundation
's String.contains(subString: String)
method.