lonespeaker
lonespeaker

Reputation: 29

Finding a value in an array of arrays

I have an array in the following format

var persons : [[String]] = []

let blah : [String] = [title, firstName, lastName, address1, town, postCode]

persons.append(blah)

Which gives output like :

[
   ["Mr", "Joe", "Bloggs", "999 Letsbe Avenue", "Townsville", "TS12 9UY"],
   ["Mr", "Peter", "Smith", "999 Underavest", "CityVille", "OP19 1IK"]
]

I want to do a search to find the first occurrence of "Smith" but I'm stumped on how to do it.

Any help please?

Upvotes: 0

Views: 94

Answers (2)

Mohammad Sadiq
Mohammad Sadiq

Reputation: 5241

You can do something like this

let array = [
       ["Mr", "Joe", "Bloggs", "999 Letsbe Avenue", "Townsville", "TS12 9UY"],
       ["Mr", "Peter", "Smith", "999 Underavest", "CityVille", "OP19 1IK"]
    ]
    
    var index = array.flatMap { $0 }.firstIndex(of: "Smith")
    print("\(index!/5)")
     index = array.flatMap { $0 }.firstIndex(of: "Bloggs")
    print("\(index!/5)")

I have taken 5 to find the index as there are five entries in each array.

enter image description here

Upvotes: 0

Shehata Gamal
Shehata Gamal

Reputation: 100503

You can try

if let index = persons.index(where:{ $0.contains("Smith")  }) { 
     print(index)  
}

Btw it's better to have

 struct Person {
    let fname,lname,address:String
 }

Upvotes: 1

Related Questions