简体   繁体   English

Int() 不会从 String 转换为 Optional Integer (Swift)

[英]Int() doesn't convert from String to Optional Integer (Swift)

I'm new at programming and started with Swift.我是编程新手,从 Swift 开始。 The first issue I came along with is the following:我遇到的第一个问题如下:

I have 4 variables我有 4 个变量

var a = "345"

var b = "30.6"

var c = "74hf2"

var d = "5"

I need to count the sum of Integers (if not integer, it will turn to nil)我需要计算整数的总和(如果不是整数,它将变为 nil)

if Int(a) != nil {
  var aNum = Int(ar)!
} 

if Int (b) != nil {
  var bNum = Int (b)! 
}       

and so on..等等..

As far as I understand, the Int() should convert each element into an Optional Integer.据我了解, Int() 应该将每个元素转换为一个可选整数。

Then I should use forced unwrapping by convertin the Int?那么我应该通过转换 Int 使用强制解包吗? to Int and only then I can use it for my purposes.到 Int,只有这样我才能将它用于我的目的。 But instead, when I count the sum of my variables, the compiler sums them as Strings.但是相反,当我计算变量的总和时,编译器将它们相加为字符串。

 var sum = aNum + bNum + cNum + dNum

Output:输出:

  34530.674hf25

Why my variables, which are declared as strings and then converted into optional integers with Int(), didn't work?为什么我的变量(声明为字符串,然后使用 Int() 转换为可选整数)不起作用?

Your code has typos that make it hard to tell what you are actually trying to do:您的代码有拼写错误,很难分辨出您实际要做什么:

Assuming your 2nd variable should be b , as below:假设您的第二个变量应该是b ,如下所示:

var a = "345"
var b = "30.6"
var c = "74hf2"
var d = "5"

///Then you can use code like this:

var sum = 0

if let aVal = Int(a) { sum += aVal }

if let bVal = Int(b) { sum += bVal }

if let cVal = Int(c) { sum += cVal }

if let dVal = Int(d) { sum += dVal }

print(sum)

That prints 350 since only 345 and 5 are valid Int values.因为只有3455是有效的 Int 值,所以打印350

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

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