Swift filter array of objects

前端 未结 7 943
忘了有多久
忘了有多久 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:14

    contains() checks if a sequence contains a given element, e.g. if a String contains a given Character.

    If your intention is to find all books where the name contains the substring "rt", then you can use rangeOfString():

    var arr = englishBooks.filter {
        $0.nameOfBook.rangeOfString("rt") != nil
    }
    

    or for case-insensitive comparison:

    var arr = englishBooks.filter {
        $0.nameOfBook.rangeOfString("rt", options: .CaseInsensitiveSearch) != nil
    }
    

    As of Swift 2, you can use

    nameOfBook.containsString("rt") // or
    nameOfBook.localizedCaseInsensitiveContainsString("rt")
    

    and in Swift 3 this is

    nameOfBook.contains("rt") // or
    nameOfBook.localizedStandardContains("rt") // or
    nameOfBook.range(of: "rt", options: .caseInsensitive) != nil
    

提交回复
热议问题