'无法在闭包体中使用可选的转换表达式的类型' [英] 'Cannot convert the expression's type' with optional in closure body

查看:124
本文介绍了'无法在闭包体中使用可选的转换表达式的类型'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了(绝对)一个我不太明白的功能。我有一个闭包,它接受 Float 并且没有返回值,aka (number:Float) - > Void 。在闭包中,我执行可选值的调用,而不是强制它的解开,因为我喜欢的行为,因为可选是一个委托(=如果它是nil,不做任何事情)。



但是当我这样做时,会得到一个错误:
无法将表达式的类型...转换为类型Float。有趣的是,当我简单地添加 println()时,错误消失了。



<我已经将我的案例简化为一个小例子:

  var可选:[String:Int]? 
let closure:(number:Int) - > Void = {(数) - >
// println()< - 当这被取消注释时,错误消失
}
code>

我打赌是编译器可能不喜欢在某些情况下我不处理浮点数,我不返回的值,那么它应该只是消失了吧?

解决方案

包含单个表达式的表达式被推断为返回该结果,因此:

  let closure:(number:Int) - > Void = {(数) - >无效
可选?.updateValue(number,forKey:key)
}

等效于:

  let closure:(number:Int) - > Void = {(数) - >在
中返回可选值?.updateValue(number,forKey:key)
}


$ b b

您现在在 Void Int?之间有冲突的返回类型(记住, updateValue 返回旧值)



使用显式回车拆分它会清楚推断出的键入。

  let closure:(number:Int) - > Void = {(数) - >无效
可选?.updateValue(number,forKey:key)
return
}

$ b b

I have come across (most definitely) a feature that I don't quite understand. I have a closure, that takes in a Float and has no return value, aka (number: Float) -> Void. In that closure, I perform a call on optional value, not forcing its unwrapping, because I like the behavior since the optional is a delegate (= if it's nil, don't do anything).

But when I do that, I get an error: Cannot convert the expression's type '...' to type Float.

Interestingly enough, when I simply add println(), the error disappears. I have simplified my case to tiny little example for illustration:

var optional: [String : Int]?
let closure: (number: Int) -> Void = { (number) -> Void in
    optional?.updateValue(number, forKey: "key")
    //println() <-- when this gets uncommented, error disappears
}

My bet would be that the compiler maybe doesn't like that in some cases I'm not handling the float number, but since I am not returning the value then it should just disappear right? What am I missing?

解决方案

An expression containing a single expression is inferred to return that result, hence:

let closure: (number: Int) -> Void = { (number) -> Void in
    optional?.updateValue(number, forKey: "key")
}

is equivalent to:

let closure: (number: Int) -> Void = { (number) -> Void in
    return optional?.updateValue(number, forKey: "key")
}

You now have conflicting return types between Void and Int? (remember, updateValue returns the old value)

Splitting it up with an explicit return clarifies the inferred typing.

let closure: (number: Int) -> Void = { (number) -> Void in
    optional?.updateValue(number, forKey: "key")
    return
}

这篇关于'无法在闭包体中使用可选的转换表达式的类型'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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