Swift代码中的可变错误

时间:2017-11-09 08:23:43

标签: swift xcode

我有一个Xcode项目有一些错误。我只对变量有问题。我将txt字符串变量转换为int,这称为txtint。当我想进行计算时,我不能因为它具有空值而不可能,因为我在函数中给出了一个值"传递"然后当我想减去时我不能,因为txtint的值为空。

//
//  ViewController.swift
//  Biophere
//
//  Created by Coder on 2017. 10. 22..
//  Copyright © 2017. Pliz Help. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var label: UILabel!
@IBOutlet weak var textview: UITextField!
@IBOutlet weak var conv: UILabel!

var text: String? = nil
var txt: String? = nil
var convert: String? = nil
var textint: Int? = nil
var txtint: Int? = nil



@IBAction func pass(_ sender: Any) {
    var txt: String {
        get {
            return textview.text ?? ""
        }
        set {
            textview.text = newValue
        }
    }
            //conv.text = txt


}




override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    label.text = text
    txt = textview.text


}

@IBAction func saveButton(_ sender: Any) {
    let textint = Int(text!)
    let txtint = Int(txt!)

    convert = String(textint! - txtint!)
    conv.text = txt
}


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


}

错误:主题1:EXC_BAD_INSTRUCTION(代码= EXC_I386_INVOP,子代码= 0x0)

1 个答案:

答案 0 :(得分:0)

var text: String = ""
var txt: String = ""
var convert: String = ""
var textint: Int = 0
var txtint: Int = 0

@IBAction func saveButton(_ sender: Any) {
    if let textint = Int(text), let txtint = Int(txt) {
        convert = String(textint - txtint)
        conv.text = txt
    }else{ 
        print("handle it")
    }    
}

建议:尝试提供变量名称描述,这是开发的基本内容。