Twitter khuong291
Twitter khuong291

Reputation: 11682

How to sum of two number of a String in 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

Upvotes: 4

Views: 14901

Answers (4)

Tyrelidrel
Tyrelidrel

Reputation: 354

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"

Upvotes: 6

vadian
vadian

Reputation: 285079

NSExpression is a fairish underestimated class in Cocoa which can do that in a pretty smart way.

let string = "1 + 2"
let arithmeticExpression = NSExpression(format: string)
let additionResult = arithmeticExpression.expressionValueWithObject(nil, context: nil) as! Int
// -> 3

Upvotes: 3

Victor Sigler
Victor Sigler

Reputation: 23451

Even if your question is only for two numbers, you can benefit from the following code using regular expressions and combining with the function map and reduce to get all the numbers in the string:

func matchesForRegexInText(regex: String!, text: String!) -> [String] {

   do {
       let regex = try NSRegularExpression(pattern: regex, options: [])
       let nsString = text as NSString
       let results = regex.matchesInString(text,
        options: [], range: NSMakeRange(0, nsString.length))
       return results.map { nsString.substringWithRange($0.range)}
   } catch let error as NSError {
       print("invalid regex: \(error.localizedDescription)")
       return []
   }
}


let string = "1 + 2 + 3 + 4"
let sum = matchesForRegexInText("[0-9]", text: string).map { Int($0)! }.reduce(0, combine: +)
print(sum) // 10

The above code use the matchesForRegexInText to extract all the numbers in the string and then with the map function convert all the numbers to Int and with the reduce function get the cumulative sum.

I hope this help you.

Upvotes: 3

Phillip Mills
Phillip Mills

Reputation: 31016

You can create a String from a Character and an Int from a String, so one possibility is:

var result = Int(String(char1))! + Int(String(char2))!

Upvotes: 3

Related Questions