ios - 凯撒密码在 Swift 上解密时出错

标签 ios swift iphone xcode

我申请系统安全主题的报告。 Caesar 的 swift 代码。我在解密阶段遇到了问题。

当我输入 key 时,程序随机排除错误:

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

或者数组退出错误

我是新手。请向我解释如何修复此错误并使我的程序正常运行。

Google 没有帮助我。

import UIKit

class CaesarCipher: UIViewController {
    @IBOutlet weak var messageText: UITextField!
    @IBOutlet weak var keyText: UITextField!
    @IBOutlet weak var cipherTextLabel: UILabel!

    ////////////////////////////////////////////////////////////////////////////

    @IBOutlet weak var cryptMessageText: UITextField!
    @IBOutlet weak var cryptKeyText: UITextField!
    @IBOutlet weak var decryptTextLabel: UILabel!

    @IBAction func cipherButton(_ sender: Any) {

        if (messageText.text == "") || (keyText.text == "")
        {
            let alert = UIAlertController(title: "Ошибка", message: "Одно, или несколько полей пустые", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "Ок", style: .default, handler: nil))
            self.present(alert, animated: true)
        }
        else
        {
            let key = keyText.text
            let e: Int32 = Int32.init(key!)!
            //let upKey: Int32 = Int32.init(&e)

            let messageCipher = messageText.text
            // var i: Int8 = Int8.init(messageCipher!)!
            //let up: UnsafeMutablePointer<Int8> = UnsafeMutablePointer<Int8>.init(&i)

            //cipherTextLabel = encrypt(up, e)
            let encryptText = cipher(messageCipher!, shift: Int(e))
            cipherTextLabel.text = "\(encryptText)"
        } 
    }

    //////////////////////////////////////////////////////////////////////////////////////////////

    @IBAction func decryptButton(_ sender: Any) {

        if (cryptMessageText.text == "") || (cryptKeyText.text == "")
        {
            let alert = UIAlertController(title: "Ошибка", message: "Одно, или несколько полей пустые", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "Ок", style: .default, handler: nil))
            self.present(alert, animated: true)
        }
        else
        {
            let cryptKey = cryptKeyText.text
            let e: Int = Int.init(cryptKey!)!
            //let upKey: Int32 = Int32.init(&e)

            let decryptMessageText = cryptMessageText.text
            // var i: Int8 = Int8.init(messageCipher!)!
            //let up: UnsafeMutablePointer<Int8> = UnsafeMutablePointer<Int8>.init(&i)

            //cipherTextLabel = encrypt(up, e)
            let decryptText = decipher(decryptMessageText!, shift2: Int(e))
            decryptTextLabel.text = "\(decryptText)"
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.hideKeyboard()
    }
}

func cipher( _ text:String, shift:Int ) -> String {

    var textCharArray:[Character] = Array( text.characters )

    let alphabet = Array("0123456789abcdefghijklmnopqrstuvxyzABCDEFGHIJKLMNOPQRSTUWVXYZ !".characters);

    let offset = alphabet.count // alphabet.length in other languages

    for i in 0 ..< text.characters.count {

        let oldChar = textCharArray[ i ]
        let oldCharIdx = alphabet.index( of:oldChar ) // get index of

        let oldCharIdxUnwrapped = oldCharIdx // oldCharIdx can be null!
        let newCharIdx = ( oldCharIdxUnwrapped! + shift + offset ) % offset

        let newChar = alphabet[ newCharIdx ]

        textCharArray[ i ] = newChar
    }

    return String( textCharArray )
}

func decipher( _ text:String, shift2:Int ) -> String {

    // when calling a function you don't have to specify the first argument...
    // For other arguments you have to specify it!
    return cipher( text, shift:shift2 * -1 )
}

最佳答案

当存在可选值(可能为 nil 的值)并且您尝试解开它(使用“!”)时,通常会引发您看到的错误。

Swift also introduces optional types, which handle the absence of a value. Optionals say either “there is a value, and it equals x” or “there isn’t a value at all”.

话虽这么说,这里的问题是 UITextfields 当“空”时其文本属性可能为 nil。所以当你这样做时

    let key = keyText.text
    let e: Int32 = Int32.init(key!)!

key 可以是零值。并且(nil)!将导致Unexpectedfound nil while unwrapping anOptional value

要解决此问题,我建议您为 UITextfield 的文本属性添加 nil 检查,或者 将 if else block 更改为以下内容

    if let key = keyText.text, let messageCipher = messageText.text, !key.isEmpty, !messageCipher.isEmpty {
        // key and messageCipher are neither nil nor empty.
    } else {
        // keyText.text or messageText.text are either nil or empty
    }

如果您对 swift 编程和制作 iOS 应用程序感兴趣,我建议您详细了解 swift 如何处理 可选 以及隐式解包的可选内容。一个起点是 https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html并跟进教程。

关于ios - 凯撒密码在 Swift 上解密时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54722360/

相关文章:

swift - 如何对组件中按下的按钮执行操作以查看 Controller

iphone - 更改编辑器iTunes应用商店的名称

ios - Xcode 7 Beta 5,UITableViewCells subview 被裁剪出 ContentView

ios - 计算属性生成 "Overriding declaration requires an ' 重写“关键字”错误

c++ - 等价于 C++ 中的 Swift 尾随闭包

iphone - 核心数据: Errors vs Exceptions Part 2

ios - Swift 中的类型转换

ios - 在 segue 之后停止对函数的预定调用

ios - AVSpeechSynthesizer 检测到说话结束?

iOS EventKit - 从日历访问我的应用程序