Как я могу упростить оператор if..else при разборе массива - PullRequest
0 голосов
/ 02 ноября 2018

У меня есть функция, которая фильтрует массив объектов и сокращает до одной строки. Массив имеет следующий формат:

[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)
        }

    }

1 Ответ

0 голосов
/ 02 ноября 2018
 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)
            }
        }

    }
...