[英]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.