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
Best Answer
Attention: Please see Leo Dabus' answer for a proper implementation for Swift 4 and Swift 5.
Swift 4 or later
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 extendingNote: This answer has been already edited, it is properly implemented and now works for substrings as well. Just make sure to use a valid range to avoid crashing when subscripting your StringProtocol type. For subscripting with a range that won't crash with out of range values you can use this implementationStringProtocol
without success, because theindex
method does not exist there.Why is this not built-in?
The error message says "see the documentation comment for discussion". Apple provides the following explanation in the file UnavailableStringAPIs.swift: