Arrays 解析数组时如何简化if..else语句
我有一个函数,它过滤一个对象数组,并将其缩减为一个字符串。数组具有以下格式:Arrays 解析数组时如何简化if..else语句,arrays,swift,Arrays,Swift,我有一个函数,它过滤一个对象数组,并将其缩减为一个字符串。数组具有以下格式: [Person(destination: “city”, surname: [“sur”, “name”]] 这是一个过滤人员以按特定姓名查找姓氏的功能 我的名字有三种状态:“约翰”,“保罗”,“詹姆斯”。我想验证每个名字是否存在,并对他的姓氏做些什么。如果不使用if…else,我怎么能做到这一点。我不喜欢这一切的样子 enum Destination: String, RawRepresentable {
[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)
}
}
当前代码中没有if…else。您的问题是为什么当前代码不工作?无论哪种方式,提供一个示例来说明您希望从给定输入中得到什么样的输出都会很有帮助。目前提供的代码甚至无法编译。你能提供吗?
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)
}
}
}