G
G
Gleb2020-07-14 15:11:37
Swift
Gleb, 2020-07-14 15:11:37

How to avoid the transition error from String to Int?

I did not know how to implement the task and found an interesting solution in JS ( https://github.com/Automedon/CodeWars-6-kyu-Soluit... ),
decided to rewrite it, but first met with map, split, reduce in swift.
Tell me what's stupid?

func evaluate(good: String, vsEvil evil: String) -> String {
    let powerGood = [0: 1,1: 2,2: 3,3: 3,4: 4,5: 10]
    let powertEvil = [0: 1,1: 2,2: 2,3: 2,4: 3,5: 5,6: 10]
    let g = good.split(separator: " ").map { (v, i, arr) in
        v * powerGood[i]! }.reduce(0, {a, b  in
        a + b
    })
    let e = evil.split(separator: " ").map { (v, i, arr) in
        v * powertEvil[i]! }.reduce(0, {a, b  in
        a + b
    })
  return g > e ? "Battle Result: Good triumphs over Evil" : g == e ? "Battle Result: No victor on this battle field" : "Battle Result: Evil eradicates all trace of Good"
}

error : Cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'Int'
error: Contextual closure type '(String.SubSequence) throws -> Int' (aka '(Substring) throws -> Int') expects 1 argument, but 3 were used in closure body

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-07-14
@shevzoom

Obviously, turn a string into a number explicitly: Int(stringValue). True, this will not help you much - there are still jambs. You can try to fix them yourself.

Or you may not try.
func worthSum(count: String, worth: [Int]) -> Int {
  return count.split(separator: " ").enumerated().reduce(0, { acc, n in
    acc + (Int(n.1) ?? 0) * worth[n.0]
  })
}

func evaluate(good: String, vsEvil evil: String) -> String {
  let g = worthSum(count: good, worth: [ 1, 2, 3, 3, 4, 10 ])
  let e = worthSum(count: evil, worth: [ 1, 2, 2, 2, 3, 5, 10 ])

  return g == e
    ? "Battle Result: No victor on this battle field"
    : g > e
      ? "Battle Result: Good triumphs over Evil"
      : "Battle Result: Evil eradicates all trace of Good"
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question