3 ms·
> Given a specific string manipulation task, I'd be happy to provide an example of what it might look like in Swift! How would you safely get the nth index of
by rudedogg 5y ago
> Given a specific string manipulation task, I'd be happy to provide an example of what it might look like in Swift!
How would you safely get the nth index of a string, clamped to the valid indexes? So if the nth index is out-of-bounds you get the first/last index instead?
- coldtea 5y agoOr you get an Optional and you have to check if there's an error or you go the character within the range? Sounds perfect safe to me...
- saagarjha 5y agoI don't think Swift has a clamping function in the standard library, unfortunately, so we'll have to roll one ourselves. One question remains of what should be done for the empty string; I've chosen to return nil for this case. extension String { func character(atClampedIndex index: Int) -> Character? { guard !self.isEmpty else { return nil } let clamped = max(0, min(index, count - 1)) return self[self.index(startIndex, offsetBy: clamped)] } }