# Why doesn't Swift allow Int String subscripting and integer ranges directly?

If I have a string:

let str = "Hello world"


It seems quite reasonable to be able to extract a character:

let thirdChar = str[3]


However, that's not legal. Instead, I have to use the extremely obtuse syntax:

let thirdChar = str[str.index(str.startIndex, offsetBy: 2)]


Similarly, why isn't str[0..<3] or str[0...2] legal? The intent is clear.

It's easy enough to create extensions to String that support those expressions:

extension String {

//Allow string[Int] subscripting
subscript(index: Int) -> Character {
return self[self.index(self.startIndex, offsetBy: index)]
}

//Allow open ranges like string[0..<n]
subscript(range: Range<Int>) -> Substring {
let start = self.index(self.startIndex, offsetBy: range.lowerBound)
let end = self.index(self.startIndex, offsetBy: range.upperBound)
return self[start..<end]
}

//Allow closed integer range subscripting like string[0...n]
subscript(range: ClosedRange<Int>) -> Substring {
let start = self.index(self.startIndex, offsetBy: range.lowerBound)
let end = self.index(self.startIndex, offsetBy: range.upperBound)
return self[start...end]
}
}


Shouldn't that be part of the language? Seems like a no-brainer.

• What is the internal encoding for strings in Swift? If it's a variable-length encoding such as UTF-8 then using a subscript operator str[3] would be misleading, because such an access cannot be made in constant time. And how does Swift define a character? Is it an Unicode code point? A visual character (grapheme) may be assembled from multiple code points. What happens if your slice includes combining characters but not the base character? Text is complicated. Not offering easy solutions that are likely to be wrong is good design. – amon Dec 9 '17 at 20:16
• I think amon is right, ive seen stuff about iphone strings with null characters and multiple character characters etc – Ewan Dec 9 '17 at 20:53
• Do you have any intention of accepting an answer here, or was this just intended as a rhetorical question / rant? – Alexander Jul 26 '18 at 16:37
• @Alexander, thanks for the kick in the pants. I lost track of this question when it was moved from SO to SE. I just accepted gnasher's answer. – Duncan C Jul 26 '18 at 19:17