简体   繁体   中英

How do i convert Swift strings into Integers?

I'm trying to make a simple program in 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? (an optional String ), which is not accepted by the Int initializer. 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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