Use Variable outside function?

Hi,

Im tying to use a variable outside of a function, I've searched many different solitons and none seem to work 😟


    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let location = locations[0]
        /
        let Speed = location.speed * 2.236936284
        SpeedLabel.text = "\(Speed)"
    }


I wish to use the variable "Speed" elsewhere in my program.. How can this be done?


Any help is appreciated


Thanks

Oliver

Accepted Reply

func locationManager is defined in a controller, most probably.


If so, just declare a var at the controller class level


var speed = Float(0)


and set it in the func:


    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let location = locations[0]
        speed = location.speed * 2.236936284
        speedLabel.text = "\(speed)"
    }


Note that var names should begin with lowercase, by Swift convention.


You could also declare

var speed : Float?


To know wether or not the value has been set.

Replies

func locationManager is defined in a controller, most probably.


If so, just declare a var at the controller class level


var speed = Float(0)


and set it in the func:


    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let location = locations[0]
        speed = location.speed * 2.236936284
        speedLabel.text = "\(speed)"
    }


Note that var names should begin with lowercase, by Swift convention.


You could also declare

var speed : Float?


To know wether or not the value has been set.

Thank you Claude!


This soluton worked great for me