在Swift中的ASCII到字元轉換的問題

來源:互聯網
上載者:User

標籤:ring   weight   rand   ref   scalar   pretty   span   rac   font   

我們在C++裡處理字元通常是這樣的

char a = ‘A‘ // A = 65printf("‘%c‘ = %d", a + 1, a + 1) // ‘B‘ = 66

這在號稱吸收C/C++所有優勢特性的Swift裡面是行不通的,因為
Character 和 Int 不能進行計算操作,會報錯

var c:Character = "A"c + 1 // 這裡是錯誤的Xcode 會告訴你 Binary operator ‘+‘ cannot be applied to operands of type ‘Character‘ and ‘Int‘

於是乎教科書裡沒有說的內容就帶來了問題

網上也沒有

但是教科書裡說到一個例子中有String.unicodeScalars可以返回字串的ASCII(或者是Unicode值)的數組。

於是 UnicodeScalar

這個類就被找到了

字元”A”可以這麼表示

let A = Character(UnicodeScalar(65))

它的值65可以這麼來

let A_ASCII = UnicodeScalar("A") // 65

在Swift中的ASCII到字元轉換的問題

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.