swiftcharacter-encodingascii

Getting character ASCII value as an Integer in Swift


I have been trying to get the character ascii code as an int so as then I can modify it and change the character by doing some math. However I am finding it difficult to do so as I get conversion errors between the different types of integers and can't seem to find an answer

     var n:Character = pass[I] //using the string protocol extension
     if n.isASCII
     {
        var tempo:Int = Int(n.asciiValue)
        temp += (tempo | key) //key and temp are of type int 
     }

Solution

  • In Swift, a Character may not necessarily be an ASCII one. It would for example have no sense to return the ascii value of "🪂" which requires a large unicode encoding. This is why asciiValue property has an optional UInt8 value, which is annotated UInt8?.

    The simplest solution

    Since you checked yourself that the character isAscii, you can safely go for an unconditional unwrapping with !:

    var tempo:Int = Int(n.asciiValue!)     // <--- just change this line
    

    A more elegant alternative

    You could also take advantage of optional binding that uses the fact that the optional is nil when there is no ascii value (i.e. n was not an ASCII character):

    if let tempo = n.asciiValue   // is true only if there is an ascii value
    {
        temp += (Int(tempo) | key) 
    }