How to search for a Character in a String with Swift 2
/Working with Strings in Swift 2 has changed significantly. There are several big upcoming changes to how you work with String.
1. String is no longer a collection type, instead the characters contained with it are accessed via a new property named characters (as mentioned on Apple’s blog).
2. Apple introduced Protocol Extensions in Swift 2 that will significantly change many APIs and functions. There’s a ton of movement from global functions (hard to find!) to methods (easier to find).
Swift 1.2 String Character Search
Searching for a Character in Swift 1.2 uses the global function contains() or find(), you won’t find them in Auto Complete – this greatly reduced the discovery of basic actions in Swift 1.2.
Using the lowercaseString property allows you to make the search case-insensitive.
// Swift 1.2 var word = "Apple" var searchCharacter: Character = "p" if contains(word.lowercaseString, searchCharacter) { print("word contains \(searchCharacter)") } if let index = find(word.lowercaseString, searchCharacter) { print("Index: \(index)") }
To make character search work for both upper and lower case, you can use the lowercaseString property on the String.
Swift 2 String Search
In Swift 2 global many functions are gone and replaced with new instance methods. Some of these transformations were one-to-one and others were renamed. Some error messages can suggest how to change your code, otherwise you may have to dig.
The contains() function has been replaced by the contains() method that can be invoked on the characters property of the new Swift 2 String.
The find() function has been replaced with a new method called indexOf() that works on your characters property.
// Swift 2 var word = "Apple" var searchCharacter: Character = "p" if word.lowercaseString.characters.contains(searchCharacter) { print("word contains \(searchCharacter)") } if let index = word.lowercaseString.characters.indexOf(searchCharacter) { print("Index: \(index)") }
Questions: the evolution of Swift
Working with Strings and Characters is fundamental for any programming language – when it’s hard to find the methods or the language uses different conventions it can be hard to figure out what code to write next.
What other functions, methods, or code tasks have you struggled with in Swift?
Reply below or on Twitter: @PaulSolt