Home > Enterprise >  App returning type optional -- needs to return type string
App returning type optional -- needs to return type string

Time:07-27

I have an app that stores user's address in the cloud, and when called upon, returns the type Optional(String) and I just want it to return a string.

Code:

import SwiftUI
import MapKit
import CoreLocationUI
import Firebase

struct Place: Identifiable {
    let id = UUID()
    var name: String
    var coordinate: CLLocationCoordinate2D
}

struct MapView: View {
    
    var empireStateBuilding =
    Place(name: "Empire State Building", coordinate: CLLocationCoordinate2D(latitude: 40.748433, longitude: -73.985656))
    
    @StateObject private var viewModel = ContentViewModel()
    
    @State var address = ""
    @State var addresses:[String] = []
    @State private var multipleAddress = ""
    
    
    let geocoder = CLGeocoder()
    @State private var result = "result of lat & long"
    @State private var lat = 0.0
    @State private var long = 0.0
    @State private var country = "country name"
    @State private var state = "state name"
    @State private var zip = "zip code"
    
    var body: some View {
        NavigationView {
            ZStack (alignment: .bottom) {
                List(0..<addresses.count, id: \.self) {i in Text(addresses[i]) }


            } 
        }
        .onAppear(perform: {
            downloadServerData()
        })
    }
    
    func downloadServerData() {
        let db = Firestore.firestore()
        db.collection("UserInfo").addSnapshotListener {(snap, err) in
            if err != nil{
                print("There is an error")
                return
            }
            for i in snap!.documentChanges {
                let documentId = i.document.documentID
                let address = i.document.get("address")
                DispatchQueue.main.async {
                    addresses.append("\(address)")
                    print(address)
                }
            }
        }
    }
    
    
    
    struct AnnotatedItem: Identifiable {
        let id = UUID()
        var name: String
        var coordinate: CLLocationCoordinate2D
    }
    
    struct MapView_Previews: PreviewProvider {
        static var previews: some View {
            MapView()
        }
    }
    
    //LocationButton
    final class ContentViewModel: NSObject, ObservableObject, CLLocationManagerDelegate  {
        @Published var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 40, longitude: 120), span: MKCoordinateSpan(latitudeDelta: 100, longitudeDelta: 100))
        
        let locationManager = CLLocationManager()
        
        override init() {
            super.init()
            locationManager.delegate = self
        }
        
        func requestAllowOnceLocationPermission() {
            locationManager.requestLocation()
        }
        
        func locationManager( _ _manager:CLLocationManager, didUpdateLocations locations: [CLLocation]){
            guard let latestLocation = locations.first else {
                // show an error
                return
            }
            DispatchQueue.main.async{
                self.region = MKCoordinateRegion(
                    center: latestLocation.coordinate,
                    span:MKCoordinateSpan(latitudeDelta:0.05, longitudeDelta:0.05))
            }
        }
        
        
        func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
            print(error.localizedDescription)
        }
    }
}

struct MapView_Previews: PreviewProvider {
    static var previews: some View {
        MapView()
    }
}

CodePudding user response:

I'm guessing you are trying to add a String address to your addresses array, from your Firebase document.

Use something like this to get a String address and append it to your addresses:

 if let address = i.document.get("address") as? String {  // <-- here
     DispatchQueue.main.async {
         addresses.append(address)  // <-- here
         print(address)
     }
 }

To understand how to unwrap optionals, read the basics, in particular: https://docs.swift.org/swift-book/LanguageGuide/OptionalChaining.html

CodePudding user response:

Inside of the function of the downloadServerData() I forgot to force unwrap it:

func downloadServerData() {
        let db = Firestore.firestore()
        db.collection("UserInfo").addSnapshotListener {(snap, err) in
            if err != nil{
                print("There is an error")
                return
            }
            for i in snap!.documentChanges {
                let documentId = i.document.documentID
                let address = i.document.get("address")!
                DispatchQueue.main.async {
                    addresses.append("\(address)")
                    print(address)
                }
            }
        }
    }
  • Related