Puneet
Puneet

Reputation: 35

How do you round a UISlider to an int in swift

I was wondering how to round a UISilder value to a int value. Right now it is displaying floats. I am using swift 3 at the moment.

     @IBOutlet var slidermove: UISlider!

     @IBAction func SliderVal(_ sender: AnyObject) {

         print(slidermove)
         let x = round(slidermove)
  }

round() does not work it will give an error, thanks for anyone that helps

Upvotes: 2

Views: 4224

Answers (2)

alexburtnik
alexburtnik

Reputation: 7741

You should round it's value instead of UISlider itself.:

let x = roundf(slider.value) // x is Float

If you need an Int instead of Float, just wrap it with Int initializer:

let x = Int(round(slider.value)) // x is Int

Upvotes: 4

Martin R
Martin R

Reputation: 539815

To round a Float to the nearest integer and get the result as an Int, the (perhaps not so well-known) function lrintf() can be used. Example:

let x = Float(12.6)
let i = lrintf(x)
print(i) // 13

In your case:

let i = lrintf(slider.value) // `i` is an `Int`

Upvotes: 1

Related Questions