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
My solution is in one line, supposing cadena is the string and 4 is the nth position that you want:
Simple... I suppose Swift will include more things about substrings in future versions.
I think that a fast answer for get the first character could be:
It's so much elegant and performance than:
But.. if you want manipulate and do more operations with strings you could think create an extension..here is one extension with this approach, it's quite similar to that already posted here:
}
BUT IT'S A TERRIBLE IDEA!!
The extension below is horribly inefficient. Every time a string is accessed with an integer, an O(n) function to advance its starting index is run. Running a linear loop inside another linear loop means this for loop is accidentally O(n2) — as the length of the string increases, the time this loop takes increases quadratically.
Instead of doing that you could use the characters's string collection.
In order to feed the subject and show swift subscript possibilities, here's a little string "substring-toolbox" subscript based
These methods are safe and never go over string indexes
I just came up with this neat workaround
Swift 4
Range and partial range subscripting using
String
'sindices
propertyAs variation of @LeoDabus nice answer, we may add an additional extension to
DefaultBidirectionalIndices
with the purpose of allowing us to fall back on theindices
property ofString
when implementing the custom subscripts (byInt
specialized ranges and partial ranges) for the latter.Thanks @LeoDabus for the pointing me in the direction of using the
indices
property as an(other) alternative toString
subscripting!Swift 4.2.
In Swift 4.2,
DefaultBidirectionalIndices
has been deprecated in favour ofDefaultIndices
.My very simple solution: