365Cases 365Cases - 3 months ago 10
Swift Question

Swift extract an Int, Float or Double value from a String (type-conversion)

Please could you help me here? I need to understand how to convert a String into an Int, Float or Double! This problem occurs when I'm trying to get the value from an UITextField and need this type of conversion!

I used to do it like this:

var myValue : Float = myTextField.text.bridgeToObjectiveC().floatValue


but since Xcode 6 beta 6 it doesn't seem to work anymore!

I've tried also like this:

var str = "3.14"

// Conversion from StringValue to an Int
var intValue : Int = str.toInt()!

// Other converstion from StringValue to an Int
var intOtherValue : Int = Int(str)

// Converstion from StringValue to a Float
var floatValue : Float = str.bridgeToObjectiveC().floatValue

// Converstion from StringValue to a Double
var doubleValue : Double = Double(str)


Please help me or tell me where I can find the answer! Many thanks!

Answer

Convert String to NSString and Use convenience methods:

var str = "3.1"

To Int

var intValue : Int = NSString(string: str).integerValue // 3

To Float

var floatValue : Float = NSString(string: str).floatValue // 3.09999990463257

To Double

var doubleValue : Double = NSString(string: str).doubleValue // 3.1


Reference

var doubleValue: Double { get }
var floatValue: Float { get }
var intValue: Int32 { get }
@availability(OSX, introduced=10.5)
var integerValue: Int { get }
@availability(OSX, introduced=10.5)
var longLongValue: Int64 { get }
@availability(OSX, introduced=10.5)
Comments