david david - 1 year ago 100
Swift Question

How to use max with swift3?

i am getting an error for the bellow code:

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

here is the error message:
no candidates produce the expected contextual result type 'cgfloat!'

this code was working without any problem on swift 2 , i don't know why i am getting that error now !

here is my real code:

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

bubbleWidth = max( CGFloat(15) ,
bubbleWidth )

and here is the error that i am receving:
enter image description here

please note: i don't want to assign value to bubbleWidth, like that
var bubbleWidth:CGFloat = -1


Answer Source

This is a consequence of SE-0054 Abolish ImplicitlyUnwrappedOptional type which has been implemented in 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.

Now one could argue that the compiler should fall back to unwrapping the optional in

bubbleWidth = max(CGFloat(15), bubbleWidth)

but for some reason that works only with a float literal

bubbleWidth = max(15, bubbleWidth)

and I am not sure if this is a bug or not. Alternatively, unwrap the value explicitly

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

or – better – provide a default value with the nil-coalescing operator ??:

bubbleWidth = max(CGFloat(15), bubbleWidth ?? 0)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download