What's the simplest way to convert from a single character String to an ASCII value in Swift?

后端 未结 14 1342
陌清茗
陌清茗 2020-11-29 01:00

I just want to get the ASCII value of a single char string in Swift. This is how I\'m currently doing it:

var singleChar = \"a\"
println(singleChar.unicodeSc         


        
14条回答
  •  余生分开走
    2020-11-29 01:39

    With Swift 5, you can pick one of the following approaches in order to get the ASCII numeric representation of a character.


    #1. Using Character's asciiValue property

    Character has a property called asciiValue. asciiValue has the following declaration:

    var asciiValue: UInt8? { get }
    

    The ASCII encoding value of this character, if it is an ASCII character.

    The following Playground sample codes show how to use asciiValue in order to get the ASCII encoding value of a character:

    let character: Character = "a"
    print(character.asciiValue) //prints: Optional(97)
    
    let string = "a"
    print(string.first?.asciiValue) //prints: Optional(97)
    
    let character: Character = "

提交回复
热议问题