/// - Parameters: 版本号对比
/// - version1: 第一个版本号
/// - version2: 第一个版本号
/// - Returns: 对比结果
/// 使用示例
/// ```let result = compareVersionNumbers("1.2.3", "1.2.4")
/// switch result {
/// case .orderedAscending:
/// print("版本1小于版本2")
/// case .orderedDescending:
/// print("版本1大于版本2")
/// case .orderedSame:
/// print("版本1等于版本2")
/// }
public static func compareVersionNumbers(_ version1: String, _ version2: String) -> ComparisonResult {
let versionComponents1 = version1.split(separator: ".").map { Int($0) ?? 0 }
let versionComponents2 = version2.split(separator: ".").map { Int($0) ?? 0 }
for (component1, component2) in zip(versionComponents1, versionComponents2) {
if component1 > component2 {
return .orderedDescending
} else if component1 < component2 {
return .orderedAscending
}
}
if versionComponents1.count > versionComponents2.count {
return .orderedDescending
} else if versionComponents1.count < versionComponents2.count {
return .orderedAscending
}
return .orderedSame
}
使用示例
let result = compareVersionNumbers("1.2.3", "1.2.4")
switch result {
case .orderedAscending:
print("版本1小于版本2")
case .orderedDescending:
print("版本1大于版本2")
case .orderedSame:
print("版本1等于版本2")
}