简体   繁体   English

将字符串转换为 int swift

[英]Convert string to int swift

I am trying to build a calculator in swift, but it does not seem to work.我正在尝试快速构建一个计算器,但它似乎不起作用。 I don't really know how to explain it but here is an example: If I sum up 1 + 2 it returns 12 instead of 3.我真的不知道如何解释它,但这里有一个例子:如果我总结 1 + 2 它返回 12 而不是 3。

Here is my code.这是我的代码。 Please note that num1 is the first part of the operation and num2 the second.请注意, num1是操作的第一部分,而num2是第二部分。

var num1 : String = ""
var num2 : String = ""

@IBOutlet weak var label: UILabel!

@IBAction func button(sender: UIButton) { 
    var currentnumber = self.label.text
    var sendertag = String(sender.tag)
    self.label.text = currentnumber! + sendertag
}

@IBAction func sum(sender: UIButton) {    
    num1 = self.label.text!
    self.label.text = ""
}

@IBAction func enter(sender: UIButton) {
    num2 = self.label.text!

    num1.toInt()
    num2.toInt()

    self.label.text = num1 + num2
}

The problem is because you're trying to sum integers but you're actually appending String since when you do问题是因为您正在尝试对整数求和,但实际上是在添加 String 的时候

self.label.text = currentnumber! + sendertag

Both are Strings (you can check the type on Xcode).两者都是字符串(您可以在 Xcode 上检查类型)。

What you want to do is add this two numbers so you have to parse them to Integer, you can achieve this by doing the following您想要做的是将这两个数字相加,以便您必须将它们解析为整数,您可以通过执行以下操作来实现

self.label.text = String(Int(current number!)! + Int(sendertag)!)

This is, first parsing to Integer both string and adding them up and then parse the result back to string because the text of the label has to be a string.也就是说,首先将两个字符串解析为 Integer 并将它们相加,然后将结果解析回字符串,因为标签的文本必须是字符串。

When you assign sum of two integer numbers into string value, It may implicitly type casting from Int to String当您将两个整数的和分配给字符串值时,它可能会隐式类型从 Int 转换为 String

Replace代替

  self.label.text = num1 + num2

with

var result: Int =num1+num2
self.label.text=String(result)

In objective c it shows up error: Xcode 4.2 or higher在目标 c 中,它显示错误:Xcode 4.2 或更高版本

Implicit conversion of 'int' to 'NSString *' is disallowed with ARC ARC 不允许将“int”隐式转换为“NSString *”

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

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