whok mok
whok mok

Reputation: 47

Converting String to Int while using reduce()

I have code:

let number: String = "111 15 111"
let result = number.components(separatedBy: " ").map {Int($0)!}.reduce(0, {$0 + $1})

First it takes given string and split into array of numbers. Next each number is converted to an integer and at the end all numbers are added to each other. It works fine but code is a little bit long. So I got the idea to get ride of map function and convert String to Int while using reduce, like this:

let result = number.components(separatedBy: " ").reduce(0, {Int($0)! + Int($1)!})

and the output is:

error: cannot invoke 'reduce' with an argument list of type '(Int, (String, String) -> Int)'

Thus my question is: Why I cannot convert String to Integer while using reduce()?

Upvotes: 0

Views: 2980

Answers (2)

Bilal
Bilal

Reputation: 19156

reduce second parameter is a closure with $0 is the result and $1 is the string. And instead of force unwrapping optional default value will be better.

let number: String = "111 15 111"
let result = number.components(separatedBy: " ").reduce(0, {$0 + (Int($1) ?? 0) })

Another alternative is with flatMap and reduce with + operator.

let result = number.components(separatedBy: " ").flatMap(Int.init).reduce(0, +)

Upvotes: 2

pacification
pacification

Reputation: 6018

Your mistake is first argument in the closure. If you look at reduce declaration, first closure argument is Result type, which is Int in your case:

public func reduce<Result>(_ initialResult: Result, 
    _ nextPartialResult: (Result, Element) throws -> Result) rethrows -> Result

So the right code will be:

let result = number.components(separatedBy: " ").reduce(0, { $0 + Int($1)! })

Upvotes: 2

Related Questions