TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

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?

2      

@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.

2      

@casj_swift

What is .1?

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

2      

@Nigel prompts a review of Tuples!

What is .1?

See -> Tuple

2      

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

2      

@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

2      

Hacking with Swift is sponsored by Superwall.

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn More

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.