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

后端 未结 27 3742
天命终不由人
天命终不由人 2020-11-22 12:32

In Objective-C the code to check for a substring in an NSString is:

NSString *string = @\"hello Swift\";
NSRange textRange =[strin         


        
27条回答
  •  暖寄归人
    2020-11-22 13:11

    From the docs, it seems that calling containsString() on a String should work:

    Swift’s String type is bridged seamlessly to Foundation’s NSString class. If you are working with the Foundation framework in Cocoa or Cocoa Touch, the entire NSString API is available to call on any String value you create, in addition to the String features described in this chapter. You can also use a String value with any API that requires an NSString instance.

    However, it doesn't seem to work that way.

    If you try to use someString.containsString(anotherString), you will get a compile time error that states 'String' does not contain a member named 'containsString'.

    So, you're left with a few options, one of which is to explicitly bridge your String to Objective-C by using bridgeToObjectiveC() other two involve explicitly using an NSString and the final one involves casting the String to an NSString

    By bridging, you'd get:

    var string = "hello Swift"
    if string.bridgeToObjectiveC().containsString("Swift") {
        println("YES")
    }
    

    By explicitly typing the string as an NSString, you'd get:

    var string: NSString = "hello Swift"
    if string.containsString("Swift") {
        println("YES")
    }
    

    If you have an existing String, you can initialize an NSString from it by using NSString(string:):

    var string = "hello Swift"
    if NSString(string: string).containsString("Swift") {
        println("YES")
    }
    

    And finally, you can cast an existing String to an NSString as below

    var string = "hello Swift"
    if (string as NSString).containsString("Swift") {
        println("YES")
    }
    

提交回复
热议问题