0

I want gave a custom Index to my code which that means the custom String/Character to read unicodeScalars for that String in that spacial position, for example this down code works with string.startIndex but I could not change it the index that I wanted, even the codes gave error in runtime for string.endIndex So I need help, right now this down code works just for index zero of string, for example I want this work for index = 1 that means B, how can I do this?

let string: String = "ABC"
let UInt32Value: UInt32 = string.unicodeScalars[string.startIndex].value
print(UInt32Value)

Update: you can replace string.startIndex with customIndex

let index: Int = 1
let customIndex: String.Index = string.index(string.startIndex, offsetBy: index)

Still need help to know why string.endIndex not working!?!

ios coder
  • 1
  • 4
  • 31
  • 91
  • You index the unicode scalars in the same way as you index the string. See https://stackoverflow.com/questions/24092884/get-nth-character-of-a-string-in-swift-programming-language/38215613#38215613 – Sweeper Mar 01 '21 at 11:17
  • @Sweeper, thanks for help, that was more about working with String length or something like that, but i got what I wanted, – ios coder Mar 01 '21 at 12:00
  • 1
    As for why `string.endIndex` is not working: `string.endIndex` is the index __past the end position__, so if you need the index of the last element of a string, you need `index(endIndex, offsetBy: -1)`. – Dávid Pásztor Mar 01 '21 at 12:10

1 Answers1

0

You can create an extension on String where you take the index as either a String.Index or an Int, then use that to subscript unicodeScalars.

extension String {
    func unicodeScalarValue(at index: String.Index) -> UInt32 {
        unicodeScalars[index].value
    }
    
    func unicodeScalarValue(at index: Int) -> UInt32 {
        unicodeScalars[self.index(startIndex, offsetBy: index)].value
    }
}

"ABC".unicodeScalarValue(at: 0)
"ABC".unicodeScalarValue(at: 1)
"ABC".unicodeScalarValue(at: 2)
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116