How can I get the nth character of a string? I tried bracket([]
) accessor with no luck.
var string = "Hello, world!"
var firstChar = string[0] // Throws error
ERROR: 'subscript' is unavailable: cannot subscript String with an Int, see the documentation comment for discussion
Swift 2.0 as of Xcode 7 GM Seed
For the nth character, replace 0 with n-1.
Edit: Swift 3.0
n.b. there are simpler ways of grabbing certain characters in the string
e.g.
let firstChar = text.characters.first
If you see
Cannot subscript a value of type 'String'...
use this extension:Swift 3
Swift 2.3
Source: http://oleb.net/blog/2014/07/swift-strings/
Swift 4.1 or later
You can extend Swift 4's StringProtocol to make the subscript available also to the substrings. Note: Due to proposal SE-0191 the extension constrain to
IndexDistance == Int
can be removed:Testing
In Swift 3 without extensions to the String class, as simple as I can make it!
myCharacter is "3" in this example.
Swift 4.2 and earlier
You will need to add this String extension to your project (it's fully tested):
Even though Swift always had out of the box solution to this problem (without String extension, which I provided below), I still would strongly recommend using the extension. Why? Because it saved me tens of hours of painful migration from early versions of Swift, where String's syntax was changing almost every release, but all I needed to do was to update the extension's implementation as opposed to refactoring the entire 300k lines-of-code production app. Make your choice.
Swift 4
String at index
Substring
First n chars
Last n chars
Swift 2 and 3
**String At Index **
Swift 2
Swift 3
SubString fromIndex toIndex
Swift 2
Swift 3
First n chars
Last n chars