简体   繁体   English

如何将 Swift 字符串转换为整数?

[英]How do i convert Swift strings into Integers?

I'm trying to make a simple program in swift.我正在尝试在 swift 中制作一个简单的程序。 Its supposed to get the users input then add it together and then display it again.它应该让用户输入,然后将其添加在一起,然后再次显示。 Im have trouble converting the strings in to integers.我无法将字符串转换为整数。 Heres my program:这是我的程序:

import UIKit
import Foundation
var str = "Adding"
let x = readLine()
let y = readLine()

//let a = Int(x) ?? 0
//let b = Int(y) ?? 0
print(x+y)

I've tried a couple different ways but it still doesn't work.我尝试了几种不同的方法,但它仍然不起作用。 Please help, thanks!请帮忙,谢谢!

readLine() returns String? readLine()返回String? (an optional String ), which is not accepted by the Int initializer. (一个可选的String ),它不被Int初始化程序接受。 You can do:你可以做:

let x = readLine() ?? ""
let y = readLine() ?? ""

let a = Int(x) ?? 0
let b = Int(y) ?? 0
print(x+y)

Try below:-试试下面: -

let x:Int = readLine()
let y:Int = readLine()

let c:Int = Int(x) + Int(y)

print(c)

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

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