Swift reduce - 为什么 value 是可选的?

标签 swift reduce enumeration

为什么totalreturn Total + 1行中是可选的?

return first.enumerated().reduce(0) { total, letter in
   let index = first.index(first.startIndex, offsetBy: letter.offset)
   if first[index] != second[index]{
       return total + 1
   }
   return total
}

Value of optional type 'Int?' must be unwrapped to a value of type'Int' Coalesce using '??' to provide a default when the optional value contains 'nil' Force-unwrap using '!' to abort execution if the optional value contains 'nil'

所以这解决了它:

return first.enumerated().reduce(0) { total, letter in
   let index = first.index(first.startIndex, offsetBy: letter.offset)
   if first[index] != second[index]{
       return total! + 1
   }
   return total
}

如果我将其分解,更改会发生在添加 let index....

确定 - 这将返回第一个的总数,并且总计不可选:

return first.reduce(0) { total, letter in
    return total + 1
}

确定 - 此枚举和总计不是可选的:

return first.enumerated().reduce(0) { total, letter in
    return total + 1
}

错误 - 这会出现编译错误,总计是可选的

return first.enumerated().reduce(0) { total, letter in
    let index = first.index(first.startIndex, offsetBy: letter.offset)
    return total + 1
}

最佳答案

为了让您得到这个结果(据我所知),封闭函数必须返回一个 Int?。这意味着 reduce 可以返回一个可选值。如果没有条件,编译器可以确定reduce永远不会返回nil,即total永远不会为零。因此,编译器推断闭包的返回类型是Int。编译器似乎正在纠缠 reduce 闭包和 total 的类型推断。添加条件后,编译器将无法确定 reduce 是否返回 nil。现在,当它不必要地推断 total 的类型时,它就会出错。

对我来说,这看起来像是 Swift 类型推断误入歧途的情况。显然,根据 enumerated 的文档,total 永远不会为零。

如果稍微修改代码,您将得到预期的结果:

   return first.enumerated().reduce(0) { (total: Int, letter) in
       let index = first.index(first.startIndex, offsetBy: letter.offset)
       if first[index] != second[index]{
          return total + 1
       }
       return total
   }

Swift 进行了大量类型推断,这真的很棒,因为我获得了强大的类型,同时保留了动态语言的许多优点。然而,根据我的经验, swift 的推论有时可能令人费解。它可以轻松地处理神秘的情况,并在我认为显而易见的事情上遇到困难。

对我来说这看起来像是一个错误。

关于Swift reduce - 为什么 value 是可选的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54163583/

相关文章:

ios - AudioKit:如何将 AKOperation 参数值设置为 Double 进行操作?

javascript - recompose 库中的 Compose 方法

c# - C# 相当于 Java 的 Enumeration<>

mockito thenReturn 中的 Java 枚举列表

c++ - C/C++ : size of a typedef struct containing an int and enum == sizeof(int)?

arrays - 如何在 swift 3/4 中使用 range.map?

ios - 如何从 json 响应创建动态节头

swift - enumerateChildNodesUsingBlock 调用时出现 "Cannot convert value"错误

javascript - 递归实现函数reduce javascript

javascript - 在 JavaScript 中计算二维数组的总和