I'm looking to do a function which take all the information of one Element of my structured array. And as I would like to do it on many array (of same Type) and many elements of this array I'd like to do a single function which take in parameter the array's name and the Array's element where I would like to work.
My array exemple :
class FlightLibrary: ObservableObject{
@Published var testFlight = [
Flight(seTime: "00:20", meTime: "", nightTime: "", ifrTime: "", captainTime: "00:20", copilotTime: "", dualTime: ""),
Flight(seTime: "00:40", meTime: "00:20", nightTime: "", ifrTime: "", captainTime: "00:20", copilotTime: "", dualTime: ""),
Flight(seTime: "00:35", meTime: "", nightTime: "00:20", ifrTime: "", captainTime: "00:20", copilotTime: "", dualTime: "")
]
}
And my attempt for my function :
func GetSpecificTotalTime(inArray: Array<Flight>, ofTime: Array<Flight>.Element) -> String{
var specificTotalTime: String = ""
var specificTimeInt: Int = 0
for i in inArray{
let stringValueToAdd: String = i.oftime
}
return specificTotalTime
}
Here I've my function where, for exemple, I'd like to work in my array testFlight
on the element .seTime
. So I would have something like :
GetSpecificTotalTime(inArray: testFlight, ofTime: seTime)
But in my function the line let stringValueToAdd: String = i.oftime
didn't work.
Here I want to fil stringValueToAdd
by the value which is on enteredArray[i].enteredElement
and after work with this value before going to the next index.
How could I do that ?
CodePudding user response:
The second parameter is not an array. Array<Flight>.Element
is just a Flight
.
A possible way is to specify a key path as second parameter for example
func getSpecificTotalTime(inArray: Array<Flight>, ofTime: KeyPath<Flight,String>) -> String {
Then you can get any string property with
for i in inArray{
let stringValueToAdd: String = i[keyPath: ofTime]
}
and call it
getSpecificTotalTime(inArray: testFlight, ofTime: \.seTime)