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

后端 未结 14 1325
陌清茗
陌清茗 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:48

    A slightly shorter way of doing this could be:

    first(singleChar.unicodeScalars)!.value
    

    As with the subscript version, this will crash if your string is actually empty, so if you’re not 100% sure, use the optional:

    if let ascii = first(singleChar.unicodeScalars)?.value {
    
    }
    

    Or, if you want to be extra-paranoid,

    if let char = first(singleChar.unicodeScalars) where char.isASCII() {
        let ascii = char.value
    }
    

提交回复
热议问题