0

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?

1
  • 1
    warning: Using arrays to model records like this is a bad idea, and will only lead you down a road of incorrect-index errors, type casting headaches and pain. It's better to use a struct or class to model your Person. At that point, the search becomes as easy and readable as people.first(where: { $0.lastName == "Smith }) Commented Nov 24, 2019 at 14:49

2 Answers 2

1

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
 }
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, that's perfect! Do you know how I can get the row number of the matching entry? like if I search for "Smith" I get 2, and if I search for "Bloggs" I get 1 ?
Thank you for your help, that's all been perfect.
0

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

1 Comment

You can use enumerated() to directly get the indices, rather than this flatMap + division trick (which will break the moment somebody adds/removes a field to the people's fields)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.