Swift filter array of objects

前端 未结 7 941
忘了有多久
忘了有多久 2021-02-03 20:44
class book{
    var nameOfBook: String!
}

var englishBooks=[book(),book(),book()]
var arr = englishBooks.filter {
    contains($0.nameOfBook, \"rt\")
}
<
7条回答
  •  [愿得一人]
    2021-02-03 21:04

    Sorry this is an old thread. Change you code slightly to properly init your variable 'nameOfBook'.

    class book{
       var nameOfBook: String!
       init(name: String) {
          nameOfBook = name
       }
    }
    

    Then we can create an array of books.

    var englishBooks = [book(name: "Big Nose"), book(name: "English Future 
    Prime Minister"), book(name: "Phenomenon")]
    

    The array's 'filter' function takes one argument and some logics, 'contains' function can take a simplest form of a string you are searching for.

    let list1 = englishBooks.filter { (name) -> Bool in
       name.contains("English")
    }
    

    You can then print out list1 like so:

    let list2 = arr1.map({ (book) -> String in
       return book.nameOfBook
    })
    print(list2)
    
    // print ["English Future Prime Minister"]
    

    Above two snippets can be written short hand like so:

    let list3 = englishBooks.filter{ ($0.nameOfBook.contains("English")) }
    print(list3.map({"\($0.nameOfBook!)"}))
    

提交回复
热议问题