我有一个过滤对象数组并将其简化为一个String的函数。数组具有以下格式:
[Person(destination: “city”, surname: [“sur”, “name”]]
此功能可过滤人员以按特定名称查找姓氏。
我有三种名称状态:“约翰”,“保罗”,“詹姆斯”。我想验证每个名字是否存在,并用他的姓氏做些什么。我如何不使用if ... else来做到这一点。我不喜欢这一切的样子。
enum Destination: String, RawRepresentable {
case city
case rural
case both
}
func findPerson(person: persons, type: Destination) -> String? {
let surname = persons.filter{ $0.destination == type.rawValue}.reduce("") { id, element in
return element.details.joined(separator: " ")
}
return surname
}
func findPersons(person: persons) {
// Also I want to verify if is not null the string that i receive
if let city = self.findPerson(person: person, type: .city) {
self.handleCity(type: city)
}
if let rural = self.findPerson(person: person, type: .rural) {
self.handleRural(type: rural)
}
if let both = self.findPerson(person: person, type: .both) {
self.handleBoth(type: both)
}
}
答案 0 :(得分:-1)
enum Destination: String, RawRepresentable {
case city
case rural
case both
static let all : [Destination] = [
.city,
.rural,
.both
]
func findPersons(person: persons) {
// Also I want to verify if is not null the string that i receive
for destination in Destination.all{
if let findPerson(person, type: destination){
self.handleCity(type: destination.rawValue)
}
}
}