【问题标题】:generic closure in the Collection protocol extension [duplicate]Collection 协议扩展中的通用闭包
【发布时间】:2021-02-21 04:31:59
【问题描述】:

我需要为所有集合编写一个名为 count(where:) 的方法,以计算通过所提供测试的元素数量。 有一个警告我希望能够这样称呼它:

let workouts: [Exercise] = [ellipticalWorkout, runningWorkout]
let hardWorkoutCount = workouts.count(where: { $0.caloriesBurned >= 500})   // 1

协议和结构声明

protocol Exercise: CustomStringConvertible {
    var caloriesBurned: Double {get set}
    var minutes: Double {get set}
    var title: String {get}
}

struct ElipticalWorkout: Exercise {
    var caloriesBurned: Double
    var minutes: Double
}

struct RunningWorkout: Exercise {
    var caloriesBurned: Double
    var minutes: Double
    var meters: Double
}

let elipticalWorkout = ElipticalWorkout(caloriesBurned: 335, minutes: 30)
let runningWorkout = RunningWorkout(caloriesBurned: 650, minutes: 25, meters: 5000)

这是我迄今为止尝试过的:(这些只是我的第一步,我认为我需要在方法中声明一个泛型类型)

extension Collection {
    func count(where arrOfBools: () -> [Bool]) -> Int {
        // here i count the true values in the arrOfBool..
        let results = arrOfBools()
        var count = 0
        for element in results {
            if element == true {
                count += 1
            }
        }
        
        return count
    }
}
var arrExample = [400,200,600].count(where: {$0 >= 500}) // it returns a compile error

【问题讨论】:

标签: swift collections protocols


【解决方案1】:

@Sweeper 的回答非常出色,而且完全正确。我认为还值得一提的是,您可以使用filtercount 来完成相同类型的事情,而无需扩展Collection

var arrExample = [400,200,600].filter({ $0 > 500 }).count

let hardWorkoutCount = workouts.filter({$0.caloriesBurned >= 500}).count

【讨论】:

  • 这会不必要地创建一个中间集合
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多