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

时间:2019-01-12 20:29:09

标签: swift reduce enumeration

为什么total在行return 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
}
  

可选类型'Int?'的值必须解包为   使用'??'输入'Int'Coalesce提供可选时的默认值   值包含'nil'使用'!'强制展开。如果中止执行   可选值包含'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 ....

确定-返回first和total的总数不是可选的:

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
}

1 个答案:

答案 0 :(得分:0)

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

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

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

   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的推论有时会令人迷惑。它可以轻松处理神秘的情况,并偶然发现我认为显而易见的内容。

对我来说似乎是个虫子。