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

后端 未结 27 3861
天命终不由人
天命终不由人 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:26

    You can do exactly the same call with Swift:

    Swift 4 & Swift 5

    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")
    }
    

    Swift 3.0+

    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")
    }
    

    Older Swift

    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

    Footnotes

    1. Just remember that using collection functions on Strings has some edge cases which can give you unexpected results, e. g. when dealing with emojis or other grapheme clusters like accented letters.

提交回复
热议问题