Dimitri T Dimitri T - 4 months ago 28
Swift Question

how to assign double value to text field in swift

How do I initialize my UITextField to be double instead of a string?

My app users enter latitude and longitude through TextFields with my IBoutlet

But I'm having trouble converting it to a double for further functions and saving in my realm database. How and where do I convert it?

@IBOutlet weak var latitudeTextField: UITextField!

@IBOutlet weak var longitudeTextField: UITextField!

func fillTextFields() {
nameTextField.text = specimen.name
latitude.TextField = specimen.latitude
longitude.TextField = specimen.longitude

}


func updateSpecimen() {
let realm = try! Realm()
try! realm.write {
self.specimen.name = self.nameTextField.text!
self.specimen.longitude = self.longitudeTextField.text!
self.specimen.latitude = self.latitudeTextField.text!
}


then further down the file the func updateSpecimen() is called again

override func shouldPerformSegueWithIdentifier(identifier: String?, sender: AnyObject?) -> Bool {
if validateFields() {
if specimen != nil {
updateSpecimen()
} else {
addNewSpecimen()
}
return true
} else {
return false
}
}

Answer

You can convert a String to Double

if let text = self.Lat.text {
    let num = Double(text)
}

Update

class ViewController {

    @IBOutlet weak var latitudeTextField: UITextField!
    @IBOutlet weak var longitudeTextField: UITextField!

    func fillTextFields() {

        guard let
            latitudeText = latitudeTextField.text,
            latitude = Double(latitudeText),
            longitudeText = longitudeTextField.text,
            longitude = Double(longitudeText)
            else {
                // tell the user to fill the fields
                return
            }

        updateSpecimen(latitude, longitude:longitude)
    }

    func updateSpecimen(latitude: Double, longitude: Double) {
        // here you can use latidute and longitude
    }

}

Update 2

You can also use these 2 computed variables

var latitude: Double? {
    if let text = latitudeTextField.text {
        return Double(text)
    } else {
        return nil
    }
}

var longitude: Double? {
    if let text = longitudeTextField.text {
        return Double(text)
    } else {
        return nil
    }
}