I\'m trying to filter an array of instances of a class. I\'d like a new array filtered by one of the class properties. Can\'t quite get my head around the way Swift filters
This should work...
let males = people.filter({ $0.gender == .male })
You may need to make your enum conform to equatable to do this comparison.
The $0 is an unnamed parameter, you could also do..
let males = people.filter({ person in
return person.gender == .male
})
EDIT: I've just tested this and it does work without making the enum conform to equatable. I think you only need to do that when the enum takes parameters.
enum TransactionMode {
case credit, debit
}
class Transaction {
public private(set) var pnr: String
public private(set) var transactionMode: TransactionMode
public private(set) var pointDescription: String
public private(set) var date: String
public private(set) var points: UInt16
init(pnr:String, transactionMode:TransactionMode, pointDescription:String, date:String, points:UInt16) {
self.pnr = pnr
self.transactionMode = transactionMode
self.pointDescription = pointDescription
self.date = date
self.points = points
}
}
lazy var transactionLists:Array<Transaction> = {
let transactions:Array<Transaction> =
[Transaction(pnr: "PQ673W", transactionMode:.debit, pointDescription: "Received SpiceCash", date: "5th Mar,2018", points: 700),
Transaction(pnr: "PQ671W", transactionMode:.credit, pointDescription: "Redeemed SpiceCash", date: "5th Jun,2018", points: 400),
Transaction(pnr: "MQ671X", transactionMode:.debit, pointDescription: "Redeemed Loyalty Points", date: "5th July,2017", points: 500),
Transaction(pnr: "PQ671L", transactionMode:.credit, pointDescription: "Received SpiceCash", date: "18th Mar,2018", points: 600),
Transaction(pnr: "PQ671D", transactionMode:.debit, pointDescription: "Redeemed SpiceCash", date: "15th Jun,2018", points: 400),
Transaction(pnr: "MQ671Q", transactionMode:.credit, pointDescription: "Redeemed Loyalty Points", date: "25th April,2017", points: 500),
Transaction(pnr: "P2671L", transactionMode:.debit, pointDescription: "Received SpiceCash", date: "18th Jan,2018", points: 1200),
Transaction(pnr: "PQ671Q", transactionMode:.credit, pointDescription: "Redeemed SpiceCash", date: "15th Feb,2018", points: 1400),
Transaction(pnr: "MQ677A", transactionMode:.debit, pointDescription: "Redeemed Loyalty Points", date: "25th April,2017", points: 1500)
]
return transactions
}()
let filteredArray = self.transactionLists.filter({
($0.pnr.localizedCaseInsensitiveContains(searchText)) || (String(format: "%d", ($0.points)).localizedCaseInsensitiveContains(searchText)) || ($0.pointDescription.localizedCaseInsensitiveContains(searchText)) || ($0.date.localizedCaseInsensitiveContains(searchText))
})
let pnr = self.transactionLists.filter({ $0.pnr == "PQ671Q"})