Home > OS >  SwiftUI Trying to find a value into an Array and save it into a Var
SwiftUI Trying to find a value into an Array and save it into a Var

Time:09-08

I've an Array based on this struct :

struct Airports2: Identifiable, Codable, Hashable{
    var AirportID: String = ""
    var Icao: String = ""
    var ApType: String = ""
    var Name: String = ""
    var Latitude: String = ""
    var Longitude: String = ""
    var Altitude: String = ""
    var Continent: String = ""
    var Country: String = ""
    var Region: String = ""
    var Municipality: String = ""
    var Service: String = ""
    var GpsCode: String = ""
    var Iata: String = ""
    var LocalCode: String = ""
    var Link: String = ""
    var wikiLink: String = ""
    var Keyword: String = ""
    let id = UUID()
}

And I would like to create a function which have as Parameter a String corresponding to the ICAO and from the ICAO find the airport Latitude and save only the Latitude in a simple var and return it.

My Airport array is declared as follow :

var FR_airportsDB = [Airports2]()

And my "searching function" is like that :

func getApLat(ApName: String) -> Double{
    
    let LAT: Double
    
    var latFindString = FR_airportsDB.contains(Airports2.init(Icao: ApName))
    
    LAT = Double(latFindString)!
    
    return LAT
}

But this is not working, I think .contains is not the best to use but I don't know how to make a search in a structured array.

Hope to be clear about my problem ..

Thanks for your help

CodePudding user response:

First of all please name your variables lowerCamelCase according to the naming convention and name your struct in singular form

var frAirportsDB = [Airport2]()

To search for a value of a specific property try to get the first item in the array where the value of this property is equal to the value in the parameter.

You have to return an optional because the item might be not available and the string could not be converted to Double

func getApLat(apName: String) -> Double? {
    
    guard let foundAirport = frAirportsDB.first(where: {$0.Icao == apName}),
          let lat = Double(foundAirport.Latitude) else { return nil }
    
    return lat
}

And please add CodingKeys to convert the uppercase keys to lowercase property names. And all default values in the struct are not necessary. The code compiles even without.

  • Related