记录一下swift 版本号比较
例如 2.1.0 高于 1.0.0 和 2.0.0
extension String {
func versionCompare(_ otherVersion: String) -> ComparisonResult {
var v1 = versionComponents()
var v2 = otherVersion.versionComponents()
let diff = v1.count - v2.count
if diff == 0 {
return self.compare(otherVersion, options: .numeric)
}
if diff > 0 {
v2.append(contentsOf: (0..<diff).map { _ in "0" })
} else {
v1.append(contentsOf: (0..<abs(diff)).map { _ in "0" })
}
return v1.joined().compare(v2.joined())
}
func versionComponents() -> [String] {
components(separatedBy: ".")
}
}
调用
print("0.1.1".versionCompare("0.1") == .orderedDescending) // true
这个方法返回一个 ComparisonResult 对象,它有三个值:
- orderedAscending:前者小于后者
- orderedSame:两者相等
- orderedDescending:前者大于后者
比较逻辑
1、首先把两个版本号按句点( . )拆分成数组
2、对比两个版本号的长度是否一致,如果一致,则利用 compare 函数直接对比
3、如果不一致,则把较短的版本号后面补 0
4、最后再用 compare 函数进行对比