测试已测试 | ✓ |
语言语言 | SwiftSwift |
许可协议 | MIT |
发布日期上次发布 | 2017年1月 |
Swift版本Swift版本 | 3.0 |
SPM支持SPM | ✗ |
由Marco Muccinelli维护。
Ferrara
是一个框架,它接受两个集合,并计算它们之间的差异。它返回插入索引、删除索引、完整匹配、部分匹配和元素移动。
Matchable
协议您的对象需要遵守Matchable
协议。此协议用于检测对象的更改。
struct Tulip: Matchable {
let color: Color
let thriving: Bool
func match(with object: Any) -> Match {
guard let tulip = object as? Tulip else {
return .none
}
if color == tulip.color {
if thriving == tulip.thriving {
return .equal
}
else {
return .change // Same color, but not thriving
}
}
else {
return .none
}
}
}
这足以计算差异。
let oldTulips: [Tulip]
let newTulips: [Tulip]
let diff = Diff(from: oldTulips, to: newTulips)
Matchable
和 Equatable
结合使用如果一个对象遵循Equatable
,则通常会提供一个基本的match(with:)
实现:如果对象相等,返回.equal
;否则返回.none
。您可以利用此扩展执行简单的差异比较,而无需更改。
extension Int: Matchable {} // Use standard match(with:) implementation
let a: [Int]
let b: [Int]
let diff = Diff(from: a, to: b)
此外,您还可以使用Equatable
简化您的自定义对象。
struct Tulip: Matchable, Equatable {
let color: Color
let thriving: Bool
static func ==(lhs: Tulip, rhs: Tulip) -> Bool {
return lhs.color == rhs.color && lhs.thriving == rhs.thriving
}
func match(with object: Any) -> Match {
guard let tulip = object as? Tulip else {
return .none
}
if self == tulip {
return .equal
}
else if color == tulip.color {
return .change
}
else {
return .none
}
}
}
另外,当一个对象遵循Matchable
时,有一个免费的==
实现。所以,如果您的偏好,您可以编写如下代码
struct Tulip: Matchable, Equatable {
let color: Color
let thriving: Bool
func match(with object: Any) -> Match {
guard let tulip = object as? Tulip else {
return .none
}
if color == tulip.color {
if thriving == tulip.thriving {
return .equal
}
else {
return .change // Same color, but not thriving
}
}
else {
return .none
}
}
}
Identifiable
协议Identifiable
协议描述了您需要一个有属性可识别的对象的常见场景。如果您还遵守Matchable
和Equatable
,您将有一个免费的match(with:)
实现。
struct Person: Identifiable, Matchable, Equatable {
let identifier: String // This is enough for Identifiable conformance
let name: String
static func ==(lhs: Person, rhs: Person) -> Bool {
return lhs.identifier == rhs.identifier && lhs.name == rhs.name
}
}
let lastYearPeople: [Person]
let thisYearPeople: [Person]
let diff = Diff(from: lastYearPeople, to: thisYearPeople)
您还可以比较混合集合,因为Diff
可以将异构集合作为输入参数。
extension Int: Matchable {}
extension String: Matchable {}
let a = ["h", 3, "l", "l", 0] as [Any]
let b = ["s", 3, "l", "l"] as [Any]
let diff = Diff(from: a, to: b) // is legal
Marco Muccinelli,[email protected]
Ferrara
采用 MIT 许可证。更多详细信息请参阅 LICENSE 文件。
Ferrara 是意大利艾米利亚-罗马涅大区的一座城市和市镇,也是 Ferrara 省的省会。由于其美丽和文化遗产,Ferrara 被联合国教科文组织列为世界遗产。它是历史上河流波河三角洲的所在地。波河流经许多重要的意大利城市,并在其流程的末端形成一个广阔的三角洲。所以,波河三角洲激发了名称的由来 :)。