Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: String contains String (Without using NSString)?

Tags:

string

swift

I have the same problem like in this question:

How do I check if a string contains another string in Swift?

But now a few months later I wonder if it can be done without using NSString? I nice and simple contains-method would be fine. I searched the web and the documentation but I found nothing!

like image 375
TalkingCode Avatar asked Sep 21 '14 09:09

TalkingCode


2 Answers

String actually provides a "contains" function through StringProtocol.
No extension whatsoever needed:

let str = "asdf"
print(str.contains("sd") ? "yep" : "nope")

enter image description here

https://developer.apple.com/reference/swift/string https://developer.apple.com/documentation/swift/stringprotocol


If you want to check if your string matches a specific pattern, I can recommend the NSHipster article about NSRegularExpressions: http://nshipster.com/nsregularexpression/

like image 120
d.felber Avatar answered Sep 28 '22 06:09

d.felber


Same way, just with Swift syntax:

let string = "This is a test.  This is only a test"

if string.rangeOfString("only") != nil {
     println("yes")
}

For Swift 3.0

if str.range(of: "abc") != nil{
     print("Got the string")
}
like image 24
Steve Rosenberg Avatar answered Sep 28 '22 06:09

Steve Rosenberg