简体   繁体   English

在Swift中从string转换为int

[英]Converting from string to int in Swift

So, I have looked at all the other questions regarding this and I've attempted to implement the suggested solutions, but to no avail. 所以,我已经查看了有关此问题的所有其他问题,并且我试图实施建议的解决方案,但无济于事。 I have two text fields in a view controller that a user enters numbers into and is then allowed to perform either an addition or subtraction of the two numbers. 我在视图控制器中有两个文本字段,用户输入数字,然后允许执行两个数字的加法或减法。 Unless I'm mistaken, the text fields are strings and need to be converted to integers before the calculation can be done. 除非我弄错了,否则文本字段是字符串,需要在计算完成之前转换为整数。 I'm not having any luck with that conversion though. 虽然我对转换没有任何好运。 Any suggestions in the right direction would be much appreciated. 任何正确方向的建议都将非常感谢。 Here is the applicable code: 以下是适用的代码:

let firstInput : Int? = Int(firstNumber)
let secondInput : Int? = Int(secondNumber)
var result = 0

@IBOutlet weak var firstNumber: UITextField!

@IBOutlet weak var secondNumber: UITextField!

@IBOutlet weak var segmentedControlCalculate: UISegmentedControl!

@IBAction func segmentedControlAddSubtract(sender: AnyObject) {
    switch segmentedControlCalculate.selectedSegmentIndex {
    case 0:
        result = firstInput+ secondInput
    case 1:
        result = firstInput - secondInput
    default:
        return
    }
    updateTotalLabel()

}

func updateTotalLabel() {
    total.text = "Total = " + String(result)
}

@IBOutlet weak var total: UILabel!

@IBAction func dismiss(sender: AnyObject) {
    dismissViewControllerAnimated(true, completion: nil)
}

A text field contains a string (in its text property); 文本字段包含一个字符串(在其text属性中); it is not itself a string. 它本身不是一个字符串。 And since that string can change, you should ask the text field for it each time you need it. 由于该字符串可以更改,因此每次需要时都应该询问文本字段。

You can use a guard let statement to unwrap all of the optionals (since each text field's text is optional, and the Int conversion also returns optional), like this: 您可以使用guard let语句来解包所有选项(因为每个文本字段的text都是可选的,而Int转换也返回可选),如下所示:

class ViewController {
    @IBOutlet weak var firstNumber: UITextField!
    @IBOutlet weak var secondNumber: UITextField!
    @IBOutlet weak var total: UILabel!
    @IBOutlet weak var segmentedControlCalculate: UISegmentedControl!

    @IBAction func segmentedControlAddSubtract(sender: AnyObject) {
        switch segmentedControlCalculate.selectedSegmentIndex {
        case 0:
            operation = (+)
        case 1:
            operation = (-)
        default:
            return
        }
        updateTotalLabel()
    }

    private var operation: ((Int, Int) -> Int)?

    private func updateTotalLabel() {
        guard let operation = operation,
            firstString = firstNumber.text,
            firstInput = Int(firstString),
            secondString = secondNumber.text,
            secondInput = Int(secondString)
            else {
                total.text = "Bogus input"
                return
        }
        let result = operation(firstInput, secondInput)
        total.text = "Total = \(result)"
    }
}
    let text1 = "4"
    let text2 = "3"
    let a = Int(text1)  //4
    let b = Int(text2)  //3
    let c =  a! + b!   //7

    print(a)  //"Optional(4)\n"
    print(c)   //7

Be sure to unwrap optionals. 务必打开选项。 Converting a String to an Int may not lead to an Int and hence the type is optional. 将String转换为Int可能不会导致Int,因此该类型是可选的。 OF course this is a simple example. 当然这是一个简单的例子。 You need to first test if a real Int was entered. 您需要首先测试是否输入了真实的Int。

So you must understand that's type mismatch on string to int is more then of int to char . 所以你必须明白,字符串到int的类型不匹配就比int更符合char During the convert you may loose some bits, but as I understand we pushed to use that :) For using as integer u can just initialize a new var with constructor. 在转换期间你可能会丢失一些位,但据我所知我们推动使用:)为了使用整数你可以用构造函数初始化一个新的var。

var string = "1234"
var number = Int(string)

You must to check the type of return of property inputs, if its a string. 您必须检查属性输入的返回类型(如果是字符串)。 Try to isolate strings and then convert, because maybe you re converting object property but not a data :) 尝试隔离字符串然后转换,因为可能你正在转换对象属性而不是数据:)

Your calculation part should be like this 你的计算部分应该是这样的

@IBAction func segmentedControlAddSubtract(sender: AnyObject) {

    // You should assign value in this stage, because there might still no value for textfield initially.
    firstInput = Int(firstNumber.text)
    secondInput = Int(secondNumber.text)

    switch segmentedControlCalculate.selectedSegmentIndex {
    case 0:
        result = firstInput+ secondInput
    case 1:
        result = firstInput - secondInput
    default:
        return
    }
    updateTotalLabel()

}

You should assign your variable inside action, and not at the beginning 您应该在行动中分配变量,而不是在开头

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM