Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Restructure variables into function or reusable single variable

So I have a structure built out as this:

struct MapView: View {

    @StateObject var locationManager = LocationManager()

    var userLatitude: String {
        return "\(locationManager.lastLocation?.coordinate.latitude ?? 0)"
    }
    var userLongitude: String {
        return "\(locationManager.lastLocation?.coordinate.longitude ?? 0)"
    }
    var userAltitude: String {
        return "\(locationManager.lastLocation?.altitude ?? 0)"
    }
    var userFloor: String {
        return "\(String(describing: locationManager.lastLocation?.floor))"
    }
    var userSpeed: String {
        return "\(locationManager.lastLocation?.speed ?? 0)"
    }
    var userSpeedAccuracy: String {
        return "\(locationManager.lastLocation?.speedAccuracy ?? 0)"
    }

    var body: some View {
        // Other code in here
    }
}

Is there a way that I can clean up all the variables and group them into a cleaner method? All help will be appreciated!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Using a KeyPath will give you a pretty short syntax:

class LocationManager: ObservableObject {
    @Published var lastLocation: CLLocation?
}

struct MapView: View {

    @StateObject var locationManager = LocationManager()

    private func getLastLocationKeyPath<T>(_ path: KeyPath<CLLocation, T>, defaultValue: String = "0") -> String where T: CustomStringConvertible {
        return "\(locationManager.lastLocation?[keyPath: path] ?? defaultValue)"
    }
    
    var body: some View {
        Text(getLastLocationKeyPath(\.coordinate.latitude))
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading