0

I am trying to cast a wrapped value from a String to a float and I can't manage to do it. I think I'm missing a little knowledge about the whole wrapped/unwrapped (?/!) thing in swift.

I'm trying to get the text from a label.

Here's my label:

@IBOutlet weak var maxDistance: UILabel!

Here's what I tried:

var max = Float(maxDistance.text)!
--> Could not find an overload for 'init' that accepts the supplied arguments

var max = Float(maxDistance.text!)
--> Cannot invoke 'init' with an argument of type '@lvalue String'

var max = Float(maxDistance!.text)
--> Cannot invoke 'init' with an argument of type '@lvalue String?'

var max = Float(maxDistance?.text)
--> Cannot invoke 'init' with an argument of type '$T4??'
jscs
  • 63,694
  • 13
  • 151
  • 195
Romain Braun
  • 3,624
  • 4
  • 23
  • 46

2 Answers2

2

This has nothing to do with "wrapped value". What you're saying is simply not Swift. There is no Swift-native provision for turning a string to a Float. You can turn it to an Int (with toInt). Otherwise, you'll have to fall into Cocoa and call floatValue. So:

 let s = "1.3"
 let f = (s as NSString).floatValue

However, the real answer is that you should not be doing this. If there is a Float underlying this text value, you should be preserving that Float as part of your data model. Pulling a number out of a view text representation totally violates MVC (model-view-controller).

matt
  • 515,959
  • 87
  • 875
  • 1,141
0

You could use the original Obj-C method floatValue like so:

var max = (maxDistance.text as NSString).floatValue
Ian MacDonald
  • 13,472
  • 2
  • 30
  • 51