How can I add two number in a string, I do this here but it doesn't work, it says at the line
var result = Int(char1) + Int(char2)
cannot invoke initializer for type 'int' with an agurment list of type '(Character)'
import UIKit
var str: String = "1 + 2"
var char1 = str[str.startIndex.advancedBy(0)]
var char2 = str[str.startIndex.advancedBy(4)]
var result = Int(char1) + Int(char2)
Edit1:
After do as @Phillip Mills said, it works, but I have one small question:
import UIKit
var str: String = "1 + 2"
var char1 = str[str.startIndex]
var char2 = str[str.endIndex] //error: Execution was interrupted, reason: EXC_BADINSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).
var result = Int(String(char1))! + Int(String(char2))!
Why str.startIndex work, but str.endIndex not work?
https://www.freewebmentor.com/2018/02/swift-program-add-two-numbers.html
If you know that the separator will be " + " then you can use
let str = "1 + 2"
let sum = str.componentsSeparatedByString(" + ").flatMap{ Int($0) }.reduce(0) { $0 + $1 }
This allows you to add more than one digit numbers and add more than two at a time i.e.:
let str = "1 + 2 + 432"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With