[英]Swift4 Playgrounds Caesar Cipher error
我正在嘗試在Swift Playgrounds中創建一個凱撒密碼,但是每當字母為“ W”時,我試圖將其移動4,而不是得到“ A”,我只會得到一個錯誤。 如果ascii碼+ shift不超過Z的ascii碼,則可以正常工作,否則我得到
錯誤:執行被中斷,原因:EXC_BAD_INSTRUCTION(代碼= EXC_I386_INVOP,子代碼= 0x0)。
這是我的代碼:
func cipher(messageToCipher: String, shift: UInt32) {
var ciphredMessage = ""
for char in messageToCipher.unicodeScalars {
var unicode : UInt32 = char.value
if char.value > 64 && char.value < 123 {
var modifiedShift = shift
if char.value >= 65 && char.value <= 90 {
while char.value + modifiedShift > 90 {
//return to A
modifiedShift -= 26
}
} else if char.value >= 97 && char.value <= 122 {
while char.value + modifiedShift > 122 {
//return to a
modifiedShift -= 26
}
}
unicode = char.value + modifiedShift
}
ciphredMessage += String(UnicodeScalar(unicode)!)
}
print(ciphredMessage)
}
誰能告訴我為什么字母+ shift的ASCII碼超過“ z”的ASCII碼時會出錯?
shift
是UInt32
。 因此,使用var modifiedShift = shift
,也可以將modifiedShift
推斷為UInt32
。 因此,當您將modifiedShift
設置為4,然后嘗試從中減去26時,這不是可接受的UInt32
值。
底線,使用帶符號整數。
問題在於, modifiedShift
的值可以為負,這對於類型為UInt32
的值是不允許的,因此,我建議在可能的情況下僅使用Int
:
// use `Int` for `shift`
func cipher(messageToCipher: String, shift: Int) {
var ciphredMessage = ""
for char in messageToCipher.unicodeScalars {
// convert to `Int`
var unicode = Int(char.value)
if unicode > 64 && unicode < 123 {
var modifiedShift = shift
if unicode >= 65 && unicode <= 90 {
while unicode + modifiedShift > 90 {
//return to A
modifiedShift -= 26
}
} else if unicode >= 97 && unicode <= 122 {
while unicode + modifiedShift > 122 {
//return to a
modifiedShift -= 26
}
}
unicode += modifiedShift
}
ciphredMessage += String(UnicodeScalar(unicode)!)
}
print(ciphredMessage)
}
注意: if case
匹配,也可以使用if case
。 以下幾行在語義上是等效的:
if unicode > 64 && unicode < 123 { ... }
if case 65..<123 = unicode { ... }
if (65..<123).contains(unicode) { ... }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.