面向对象编程与函数式编程:原理、实践与拓展
1. 面向对象与函数式编程基础方法
在编程实践中,我们常常需要根据特定条件从数据集合中筛选出符合要求的元素。例如,在游戏数据管理中,我们可能需要根据游戏的最高得分和游玩次数来获取特定的游戏。下面是两种等价的 getGameByHighestScoreAndPlayedCount 方法的实现:
public func getGameByHighestScoreAndPlayedCount(highestScore: Int,
playedCount: Int) -> Game? {
return getAll().filter({
(game: Game) -> Bool in
game.highestScore == highestScore && game.playedCount ==
playedCount
}).first
}
public func getGameByHighestScoreAndPlayedCount(highestScore: Int,
playedCount: Int) -> Game? {
return getAll().filter({ $0.highestScore == highestScore &&
$0.playedCount == playedCount }).first
}
这两种方法都实现了根据传入的最高得分和游玩次数筛选游戏的功能。第一种方法使用了完整的闭包语法,明确指
超级会员免费看
订阅专栏 解锁全文
1631

被折叠的 条评论
为什么被折叠?



