带有解密的Swift错误的Caesar密码

时间:2019-02-16 11:02:12

标签: ios swift iphone xcode

我申请了有关系统安全性主题的报告。 Caesar的快速代码。并且在解密阶段遇到了一个问题。

当我输入密钥时,程序会随机剔除错误:

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 )
}

1 个答案:

答案 0 :(得分:0)

当看到一个Optional(一个可能为nil的值)并且尝试将其解包(使用'!')时,通常会抛出该错误。

  

Swift还引入了可选类型,用于处理不存在的   值。可选说“有一个值,它等于x”或   “根本没有价值”。

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

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

key可以为nil值。而(nil)!将产生Unexpectedly found nil while unwrapping an Optional value

要解决此问题,建议您为UITextfield的text属性添加一个nil检查,或者 将您的if else块更改为以下

    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
    }

如果您对iOS的快速编程和制作应用程序感兴趣,建议您进一步了解如何快速处理optional和隐式展开的可选内容。一个开始的地方是https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html,然后继续学习教程。