代码之家  ›  专栏  ›  技术社区  ›  whok mok

使用reduce()时将字符串转换为Int

  •  0
  • whok mok  · 技术社区  · 6 年前

    我有代码:

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

    首先,它接受给定的字符串并拆分为数字数组。接下来,将每个数字转换为整数,最后将所有数字相加。它工作正常,但代码有点长。所以我想在使用reduce时使用map函数并将字符串转换为Int,如下所示:

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

    输出为:

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

    因此,我的问题是:为什么在使用reduce()时无法将字符串转换为整数?

    2 回复  |  直到 6 年前
        1
  •  2
  •   Bilal hao zou    6 年前

    reduce 第二个参数是带有 $0 是结果和 $1 是字符串。而不是强制展开可选的默认值会更好。

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

    另一种选择是 flatMap 减少 具有 + 操作人员

    let result = number.components(separatedBy: " ").flatMap(Int.init).reduce(0, +)
    
        2
  •  2
  •   pacification    6 年前

    你的错误是结束语中的第一个论点。如果你看 reduce 声明,第一个闭包参数为 Result 类型,即 Int 在您的情况下:

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

    因此,正确的代码是:

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