2

Before Beta 5 I could use

var str = "Hello, playground"
str.bridgeToObjectiveC().containsString("Hello")

But this is not longer supported, is there a nice workaround for this, or does Swift already offer it now?

Binarian
  • 12,296
  • 8
  • 53
  • 84
Fabian Boulegue
  • 6,476
  • 14
  • 47
  • 72
  • 1
    possible duplicate of [How do I check if a string contains another string in Swift?](http://stackoverflow.com/questions/24034043/how-do-i-check-if-a-string-contains-another-string-in-swift) – ThomasW Aug 27 '14 at 09:19

4 Answers4

1

you can use:

var str = "Hello, playground"

if str.rangeOfString("Hello") != nil {
    println("exists")
}
derdida
  • 14,784
  • 16
  • 90
  • 139
1

Just cast it explicitly to NSString:

var str = "Hello, playground"
(str as NSString).containsString("Hello")

However if there's a pure swift way to do that, I would use it - it's always better to avoid bridging unless really needed.

Antonio
  • 71,651
  • 11
  • 148
  • 165
1

In Swift is it called rangeOfString

"hello".rangeOfString("ell")

returns a range

{Some "1..<4"}

Binarian
  • 12,296
  • 8
  • 53
  • 84
1

You can write extension contains:

extension String {

    func contains(find: String) -> Bool{
       if let temp = self.rangeOfString(find){
          return true
       }
       return false
     }
}

Example:

var value = "Hello world"

println(value.contains("Hello")) // true
println(value.contains("bo"))    // false
Maxim Shoustin
  • 77,483
  • 27
  • 203
  • 225