10

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!

1

4 Answers 4

27

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")
}
Sign up to request clarification or add additional context in comments.

8 Comments

what about "is", can i get the last "is"?
@Zam In that case, it will returns the first coincidence/match for is, and if you print the range you will get something like 2..<4 {^_^} --> if let range = string.rangeOfString("is") { print(range) }
Is that syntax still used in Swift 2 ?
rangeOfString is an NSString method.
|
2

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/

3 Comments

That's check if the string contains а certain character!
@EmilMarashliev That is true. But additionally you can check anything that conforms to the StringProtocol - so it also works for String.
Ha, you're completely right it comes from StringProtocol 👉 developer.apple.com/documentation/swift/stringprotocol/… it's more convenient and elegant way than range(of:)
0

I wrote an extension on String for SWIFT 3.0 so that i could simply call absoluteString.contains(string: "/kredit/")

extension String {
  public func contains(string: String)-> Bool {
      return self.rangeOfString(string) != nil
  }

}

Comments

0

just to demonstrate the use of options.

var string = "This is a test.  This is only a test. Not an Exam"

if string.range(of:"ex") != nil {
    print("yes")
}
if string.range(of:"ex", options: String.CompareOptions.caseInsensitive) != nil {
    print("yes")
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.