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
There's an alternative, explained in String manifesto
Attention: Please see Leo Dabus' answer for a proper implementation for Swift 4.
Swift 4
The
Substring
type was introduced in Swift 4 to make substrings faster and more efficient by sharing storage with the original string, so that's what the subscript functions should return.Try it out here
To convert the
Substring
into aString
, you can simply doString(string[0..2])
, but you should only do that if you plan to keep the substring around. Otherwise, it's more efficient to keep it aSubstring
.It would be great if someone could figure out a good way to merge these two extensions into one. I tried extending
StringProtocol
without success, because theindex
method does not exist there.Swift 3:
Why is this not built-in?
Apple provides the following explanation (found here):
No indexing using integers, only using
String.Index
. Mostly with linear complexity. You can also create ranges fromString.Index
and get substrings using them.Swift 3.0
Swift 2.x
Note that you can't ever use an index (or range) created from one string to another string
As an aside note, there are a few functions applyable directly to the Character-chain representation of a String, like this:
The result is of type Character, but you can cast it to a String.
Or this:
:-)
In Swift 3
Using characters would do the job. You can quickly convert the String to an array of characters that can be manipulated by the CharacterView methods.
Example:
(full CharacterView doc)
(tested in Swift 3)