1. 程式人生 > >[Swift]ASCII值的獲取和轉換:擴充套件Character類和Int類

[Swift]ASCII值的獲取和轉換:擴充套件Character類和Int類

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 get { 7 return Character(UnicodeScalar(self)!) 8 } 9 }