Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
475 views
in Technique[技术] by (71.8m points)

ios - Swift startsWith method?

Is there such thing as a startsWith() method or something similar in Swift?

I'm basically trying to check if a certain string starts with another string. I also want it to be case insensitive.

As you might be able to tell, I'm just trying to do a simple search feature but I seem to be failing miserably at this.

This is what I'd like:

typing in "sa" should give me results for "San Antonio", "Santa Fe", etc. typing in "SA" or "Sa" or even "sA" should also return "San Antonio" or "Santa Fe".

I was using

self.rangeOfString(find, options: NSStringCompareOptions.CaseInsensitiveSearch) != nil 

prior to iOS9 and it was working just fine. After upgrading to iOS9, however, it stopped working and now searches are case sensitive.

    var city = "San Antonio"
    var searchString = "san "
    if(city.rangeOfString(searchString, options: NSStringCompareOptions.CaseInsensitiveSearch) != nil){
        print("San Antonio starts with san ");
    }

    var myString = "Just a string with san within it"

    if(myString.rangeOfString(searchString, options: NSStringCompareOptions.CaseInsensitiveSearch) != nil){
        print("I don't want this string to print bc myString does not start with san ");
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

use hasPrefix instead of startsWith.

Example:

"hello dolly".hasPrefix("hello")  // This will return true
"hello dolly".hasPrefix("abc")    // This will return false

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...