I have two ways of writing the same code, one of which seems to be disliked by the Swift compiler. Can you please explain why?
Context:
let guaranteedValue: String
let cursorPositionFromEnd: Int
Working code:
let stringFromEndUntilCursorPosition = String(guaranteedValue.reversed()[0..<cursorPositionFromEnd])
Non-working code:
let reversedOriginalString = guaranteedValue.reversed()
let stringFromEndUntilCursorPosition = String(reversedOriginalString[0..<cursorPositionFromEnd])
Compiler error message: "Cannot subscript a value of type ReversedCollection<String>
with an index of type Range<Int>
"
Other working attempt:
let reversedOriginalString = guaranteedValue.reversed()[0..< cursorPositionFromEnd]
let stringFromEndUntilCursorPosition = String(reversedOriginalString)
Basically the idea is you can only subscript a reversed range {but probably not only} if you add the index at a function return, but that does not work if you first reference the variable with a let or var and then try subscripting it.
I also understand that it would probably work in the "non-working code" if the Range would be String.Index type or whatever is the new fashion of doing it.
Can anyone explain why? Is this a bug in Swift's compiler which already has enough "twisted" string logic?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…