Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum of two number of a String in Swift

Tags:

string

swift

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

like image 748
Khuong Avatar asked Dec 06 '22 19:12

Khuong


1 Answers

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"
like image 63
Tyrelidrel Avatar answered Jan 09 '23 09:01

Tyrelidrel