[Swift]ASCII值的获取和转换:extension Character类和extension Int

时间:2021-08-25 02:39:59

Character转ASCII整数值:

 1 //Character扩展方法  
 2 extension Character  
 3 {  
 4   //转ASCII整数值(定义小写为整数值)
 5    var ascii: Int {
 6         get {
 7             let s = String(self).unicodeScalars
 8             return Int(s[s.startIndex].value)
 9         }
10     }
11     
12    //Character转ASCII整数值
13     func toInt() -> Int  
14     {  
15         var num:Int = Int()
16         for scalar in String(self).unicodeScalars  
17         {  
18             num = Int(scalar.value)  
19         }  
20         return num  
21     }  
22 }

ASCII整数值转Character:

1 //Int扩展方法  
2 extension Int
3 {
4     //属性:ASCII值(定义大写为字符值)
5     var ASCII:Character 
6     {
7         get {return Character(UnicodeScalar(self)!)}
8     }
9 }