如何在 swift3 中使用 max?

How to use max with swift3?

我收到以下代码的错误:

var bubbleWidth:CGFloat!
bubbleWidth:CGFloat = max( CGFloat(15) , bubbleWidth )

这是错误信息: 没有候选人产生预期的上下文结果类型'cgfloat!'

这段代码在 swift 2 上运行没有任何问题,我不知道为什么我现在会收到这个错误!

编辑: 这是我的真实代码:

    var bubbleWidth:CGFloat!
        bubbleWidth = imageView.frame.width + 11

    bubbleWidth =   max( CGFloat(15) ,
                          bubbleWidth )

这是我收到的错误:

编辑: 请注意:我不想像那样给 bubbleWidth 赋值 var bubbleWidth:CGFloat = -1

谢谢

这是 SE-0054 Abolish ImplicitlyUnwrappedOptional type 的结果,已在 Swift 3:

中实施

However, the appearance of ! at the end of a property or variable declaration's type no longer indicates that the declaration has IUO type; rather, it indicates that (1) the declaration has optional type, and (2) the declaration has an attribute indicating that its value may be implicitly forced. ...

If the expression can be explicitly type checked with a strong optional type, it will be. However, the type checker will fall back to forcing the optional if necessary.

现在有人可能会争辩说编译器应该回退到展开

中的可选
bubbleWidth = max(CGFloat(15), bubbleWidth)

但出于某种原因,它仅适用于浮点数 literal

bubbleWidth = max(15, bubbleWidth)

而且我不确定这是否是错误。或者,显式展开值

bubbleWidth = max(CGFloat(15), bubbleWidth!)

或者 – 更好 – 为空合并运算符提供默认值 ??:

bubbleWidth = max(CGFloat(15), bubbleWidth ?? 0)