NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

SOLVED: Unwrapping Double? in Binding

Forums > SwiftUI

Hi all,

In the following code, I want to force-unwrap a Double?, radii.1 (the one in the Slider):

if shape.radii.1 != nil {
Slider(value: $shape.radii.1, in: 100...150)
}

However, just adding an exclamation mark after radii.1 in the Slider doesn't work, because then Swift throws an error, which as far as I understand means that it thinks that I want to unwrap the whole Binding instead of the optional radii.1. Does anyone know how to fix this?

   

@Cas is sliding into trouble:

I want to force-unwrap a Double?, the one in the Slider

Take a look at SwiftUI documentation for a Slider initializer. (This is a skill you need to learn!)

See -> Official Slider Documentation

init<V>(
    value: Binding<V>,
    in bounds: ClosedRange<V> = 0...1,
    onEditingChanged: @escaping (Bool) -> Void = { _ in }
) where V : BinaryFloatingPoint, V.Stride : BinaryFloatingPoint  // <--- READ THE FINE PRINT

The initializer will build a Slider that slides over a range of type (V) and save the selected value to a binding also of type (V). The fine print however says that type must conform to the BinaryFloatingPoint protocol.

Even if you check to see that your Optional-Double does not contain nil, you should understand the compiler still sees the variable as an Optional-Double.

Values of type Optional-Double do not conform to the BinaryFloatingPoint protocol.

   

@casj_swift

What is .1?

Does it need to be optional can you give it a deflaut value (say 125)!

   

@Nigel prompts a review of Tuples!

What is .1?

See -> Tuple

   

Thank you for your reactions. I fixed it by making the optional a non-optional and giving it a default value, like NigelGee suggested.

   

@Obelix yes but you can put labels on Tuples so that they are more readable then .1 eg

(xAxis: Double, yAxis: Double)

then it would read

$shape.radii.yAxis

   

Hacking with Swift is sponsored by Judo

SPONSORED Let’s face it, SwiftUI previews are limited, slow, and painful. Judo takes a different approach to building visually—think Interface Builder for SwiftUI. Build your interface in a completely visual canvas, then drag and drop into your Xcode project and wire up button clicks to custom code. Download the Mac App and start your free trial today!

Try now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.