简体   繁体   中英

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?

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
 }

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.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM