0

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?

2 Answers 2

0

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)
0
-1

we can access the element using the array index with the help of subscript syntax. In subscript syntax, we use the index of the element (that we want to access) within square brackets, just after the name of the array.

array_Name[index_number]

1
  • As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Apr 18, 2024 at 11:07

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.