修剪阵列的有效方法

时间:2016-08-23 16:20:22

标签: arrays swift

假设我有一个结构......

struct Person {
   let isMale: Bool
   let name: String
}

和一组Person结构。我想从数组的 start end 中修剪所有人(isMale == true)(类似于从一开始就修剪空白的方式)字符串的结尾)...

func trimMen(people: [Person]) -> [Person]

    var trimmedPeople: [Person] = people

    while trimmedPeople.first?.isMale {
        trimmedPeople.removeFirst()
    }
    while trimmedPeople.last?.isMale {
        trimmedPeople.removeLast()
    }
    return trimmedPeople
}

以Swift方式有更有效的方法吗?

1 个答案:

答案 0 :(得分:3)

我能想到的最短路是:

//Find the first occurrence of a non-male person
let firstIndex = people.index(where: {!$0.isMale}) ?? 0

//Find the last occurrence of a non-male person and calculate the end index accordingly
let lastIndex = people.count - 1 - 
                (people.reversed().index(where: {!$0.isMale}) ?? 0)

//Create an array of the subsequence.
let trimmedPeople = Array<Person>(people[firstIndex...lastIndex])