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
I just had the same issue. Simply do this:
Swift 3
Usage
Helpful Programming Tips and Tricks (written by me)
Update for swift 2.0 subString
Swift3
You can use subscript syntax to access the Character at a particular String index.
Visit https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/StringsAndCharacters.html
or we can do a String Extension in Swift 4
USAGE:
A python-like solution, which allows you to use negative index,
could be:
By the way, it may be worth it to transpose the whole python's slice notation
Swift 2.2 Solution:
The following extension works in Xcode 7, this is a combination of this solution and Swift 2.0 syntax conversion.