Home > OS >  Restructure variables into function or reusable single variable
Restructure variables into function or reusable single variable

Time:10-15

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!

CodePudding user response:

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))
    }
}
  • Related