Dear Erica, what is the best way to string.contains(substring) … without Foundation?
Of course, after this initial query, I was told what he wanted was really
hasPrefix and not
contains. This led me on a merry chase through
strstr and a bunch of other ridiculous approaches, until Mike Ash suggested using
startsWith and SequenceType.
contains ended up being pretty brute force (there’s a better version by Oisin K below) but
prefixedBy does what seems to be needed. I renamed it so it didn’t overlap with the existing OS X
And here’s the much nicer version from Oisin Kidney, which performs a kind of
Oisin points out that you also may want to check out this Swift version of the Boyer-Moore algorithm by Marcin Krzyżanowski.
So I probably could have spent a half an afternoon more productively but it was nice to dive back into C interop, especially touching base with pointers (
strstr returns a pointer offset, so no Swift value types thank you) and remembering how to allocate, write to, and use memory directly. So not a complete waste.
It should be noted that my limited interest in diacriticals and other niceties would have come into play eventually. Using Swift-specific solutions offer a much better approach.