当正确定义所有类型时,为什么Swift的reduce函数会抛出“表达式类型模糊而没有更多上下文”的错误? [英] Why does Swift's reduce function throw an error of 'Type of expression ambigious without more context' when all types are properly defined?

查看:51
本文介绍了当正确定义所有类型时,为什么Swift的reduce函数会抛出“表达式类型模糊而没有更多上下文”的错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var nums = [1,2,3]

let emptyArray : [Int] = []
let sum1 = nums.reduce(emptyArray){ $0.append($1)}
let sum2 = nums.reduce(emptyArray){ total, element in
    total.append(element)
}
let sum3 = nums.reduce(emptyArray){ total, element in
    return total.append(element)
}

对于这三种方法,我都会遇到以下错误:

For all three approaches I'm getting the following error:


表达式类型含糊不清,没有更多上下文

Type of expression ambiguous without more context

但是查看文档和reduce的方法签名:

But looking at documentation and the method signature of reduce:

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

您可以看到结果 Element 可以正确推断。结果显然是 [Int] 类型,而Element是 [Int] 类型。

You can see that both the Result and Element can be correctly inferred. Result is obviously of type [Int] and Element is of type [Int].

所以我不确定这是怎么回事。我还看到了此处,但是

So I'm not sure what's wrong. I also saw here but that doesn't help either

推荐答案

您是正确的,您正在传递要推断的正确类型。 该错误具有误导性

You're right that you're passing the correct types to be inferred. The error is misleading.

您改为写道:

func append<T>(_ element: T, to array: [T]) -> [T]{
    let newArray = array.append(element)
    return newArray
} 

然后编译器将给出正确错误:

Then the compiler would have given the correct error:


不能使用变异成员不可变值:'array'是一个'let'
常量

Cannot use mutating member on immutable value: 'array' is a 'let' constant

现在我们知道正确的错误应该是什么一直是:

So now we know what the correct error should have been:

结果和元素在闭包内都是不可变的。您必须像普通的 func add(a:Int,b:Int)->那样考虑它。 Int 其中 a & b 都是不可变的。

That is both the Result and the Element are immutable within the closure. You have to think of it just like a normal func add(a:Int, b:Int) -> Int where a & b are both immutable.

如果您希望它起作用,则只需要一个临时变量即可:

If you want it to work you just need a temporary variable:

let sum1 = nums.reduce(emptyArray){
    let temp = $0
    temp.append($1)
    return temp
}

还请注意,以下是错误的!

let sum3 = nums.reduce(emptyArray){ total, element in
    var _total = total
    return _total.append(element)
}

为什么?

因为 _total.append(element)的类型是 Void ,所以它是一个函数。它的类型是 not ,而不是 5 + 3 的类型,即 Int [5] + [3] 即[Int]

Because the type of _total.append(element) is Void it's a function. Its type is not like the type of 5 + 3 ie Int or [5] + [3] ie [Int]

因此您必须这样做:

let sum3 = nums.reduce(emptyArray){ total, element in
    var _total = total
    _total.append(element)
    return _total
}

这篇关于当正确定义所有类型时,为什么Swift的reduce函数会抛出“表达式类型模糊而没有更多上下文”的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆