为什么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
}
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/