Home > front end >  Swift get decimal value for String characters
Swift get decimal value for String characters

Time:05-21

Is it possible to get the decimal value for String characters in Swift?

something like:

let words:String = "1 ring to rule them all"
var value:Int = 0

for i in 0..<words.count {
    let char = words[words.index(words.startIndex,offsetBy:i)]
    value  = Int(char.decimal)
}

where the first character in "1 ring to rule them all" is 49. Possible?

CodePudding user response:

you could try this:

let words = "1 ring to rule them all"
var value: Int = 0

for i in 0..<words.count {
    let char = words[words.index(words.startIndex,offsetBy:i)]
    if let val = char.asciiValue {
        print("----> char: \(char)  val: \(val)") // char and its "decimal" value
        value  = Int(val)
    }
}
print("\n----> value: \(value) \n") // meaningless total value

CodePudding user response:

ok, looks like this is the way:

let characterString = "蜇"
let scalars = characterString.unicodeScalars
let ui32:UInt32 = scalars[scalars.startIndex].value
  • Related