@shevzoom
 dev., student at MEPhI

Как избежать ошибки перехода от String к Int?

Не знал, как реализовать задачку и нашел интересное решение на JS ( https://github.com/Automedon/CodeWars-6-kyu-Soluit... ) ,
решил переписать, но впервые встретился с map, split, reduce в swift.
Подскажите в чем глупости?
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
  • Вопрос задан
  • 186 просмотров
Решения вопроса 1
0xD34F
@0xD34F
Очевидно, превращать строку в число явным образом: Int(stringValue). Правда, вам это не сильно поможет - есть ещё косяки. Можете попытаться исправить их самостоятельно.

А можете и не пытаться.
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"
}
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы