There is an English-language saying: “needle in a haystack”, which refers to the difficulty of finding a needle in a haystack, since both needles and hay leaves are long and skinny, and haystacks are usually pretty big compared to needles.
Let's say you have a big chunk of text, your “haystack”. You want to know where in that haystack you can find a small chunk of text, your “needle”. You can use the rangeOfString message to find the needle in the haystack.
Here's an example:
$ xcrun swift -framework Foundation 1> import Foundation 2> let haystack: NSString = "the function to find some specify thing in the string" haystack: NSString = "the function to find some specify thing in the string" 3> let needle: NSString = "function" needle: NSString = "function" 4> haystack.rangeOfString("function") $R0: NSRange = location=4, length=8 5>
The rangeOfString message returns an NSRange, which contains two parts:
location is the index where the needle starts in the haystack. The index of the beginning of the haystack is zero. length is the length of the needle.
You may have noticed that length isn't really necessary because you can just ask the needle for its length (needle.length). But NSRange is used for other things where the length part might not be obvious.
If the needle isn't in the haystack, rangeOfString returns a funny-looking location:
5> haystack.rangeOfString("Ethan Joe") $R1: NSRange = location=9223372036854775807, length=0
Say what? Well, it's actually returning a constant called NSNotFound:
6> NSNotFound $R2: Int = 9223372036854775807
You can use that constant to check whether the needle was missing:
7> if haystack.rangeOfString("Ethan Joe").location == NSNotFound { 8. println("Where did he go?") 9. } Where did he go?