How-To: Substrings in Swift
Article #8 in a 9-part series.
- 1 - Programming Problem: Determine if Two Strings Are Anagrams
- 2 - Programming Problem: Sum-Zero Triplet
- 3 - Programming Problem: Palindromes
- 4 - Problem: Validate a Phone Number
- 5 - Programming Problem: Single-Edit Difference
- 6 - Prime Factors Problem 1: LCM
- 7 - Prime Factors Problem 2: Largest Prime Factor
- 8 - this article
- 9 - Programming Problem: Pangram
Extracting a character or sub-string in the Swift programming language may seem less intuitive for programmers familiar with Java or C. One interesting difference is the CharacterView to access the length (count) of a string such as aString.characters.count. Swift String includes subscript notation by String.Index instead of an Integer, and the substring takes a Range or ClosedRange as argument. Let’s go over some code to see it in action.
updated for Swift 5
Accessing a character within a string appears a bit verbose. It helps to think of a String in Swift as not an array of characters, but as Unicode scalars, accessible with String.unicodeScalars. String.Index keeps track of the character indices. As you can see from the example above where I updated the end variable, ClosedRange includes end boundry and Range does not.
Of course, one could extend String to allow using Integer subscript. Keep in mind that in some situations (Unicode or character?) this may add ambiguity. Swift wants us to be explicit.
Article #8 in a 9-part series.
- 1 - Programming Problem: Determine if Two Strings Are Anagrams
- 2 - Programming Problem: Sum-Zero Triplet
- 3 - Programming Problem: Palindromes
- 4 - Problem: Validate a Phone Number
- 5 - Programming Problem: Single-Edit Difference
- 6 - Prime Factors Problem 1: LCM
- 7 - Prime Factors Problem 2: Largest Prime Factor
- 8 - this article
- 9 - Programming Problem: Pangram