swift - 如何比较两个版本
问题描述
我正在尝试比较两个版本的程序,但我无法输入大于 Integer 的版本,因为 .numeric 占数字的一部分,我认为 - 整数大小,并进行比较。请帮助我在比较功能中转换为另一种类型或制作其他解决方案进行比较。
import Foundation
func versionFormatting(version:inout String) {
version = String(version
.unicodeScalars
.filter(CharacterSet
.decimalDigits
.union(CharacterSet(charactersIn: "."))
.contains))
if version[version.startIndex] == "." {
version.insert("0", at: version.startIndex)
}
if version[version.index(before: version.endIndex)] == "." {
version.insert("0", at: version.endIndex)
}
version = version.replacingOccurrences(of: "..", with: ".0.")
version = version.replacingOccurrences(of: "..", with: ".0.")
}
func compareVersions(first: String, second: String) -> Int {
let firstVersion = first.components(separatedBy: ".")
let secondVersion = second.components(separatedBy: ".")
let collectiveCount = min(firstVersion.count, secondVersion.count);
for i in 0..<collectiveCount {
if firstVersion[i].compare(secondVersion[i], options: .numeric) == .orderedDescending {
return 0
}
else if secondVersion[i].compare(firstVersion[i], options: .numeric) == .orderedDescending {
return 1
}
}
let maxLengthArray: [String]
let versionIndex: Int
if firstVersion.count == collectiveCount {
maxLengthArray = secondVersion
versionIndex = 1
}
else {
maxLengthArray = firstVersion
versionIndex = 0
}
for i in collectiveCount..<maxLengthArray.count {
if maxLengthArray[i].compare("0", options: .numeric) == .orderedDescending {
return versionIndex
}
}
return -1
}
//print ("First version: ")
//var firstVersion = readLine()!
var firstVersion = "1.0.0.0"
//print ("Second version: ")
//var secondVersion = readLine()!
var secondVersion = "1.0.0"
versionFormatting(version:&firstVersion)
versionFormatting(version:&secondVersion)
print(firstVersion)
print(secondVersion)
var result = compareVersions(first:firstVersion, second:secondVersion)
if result == -1 {
print("версии равны")
}
else if result == 0 {
print("первая версия актуальнее")
}
else {
print("вторая версия актуальнее")
}
解决方案
您应该使用数字比较。例如,我想将我的 iOS 版本与 iOS 13 版本进行比较。
let systemVersion = UIDevice.current.systemVersion
if systemVersion.compare("13.0", options: .numeric) != .orderedAscending {
// >= 13.0
}
推荐阅读
- python-3.x - 有没有办法在使用神经网络生成器时解决 InvalidArgumentError?
- python - 尝试编写自定义排序函数时出错
- android - Android Studio 虚拟设备模拟器在 Dell XPS 15 Windows 10 上不起作用(不可见)
- javascript - Nodejs,试图将var导出到另一个文件
- python - 迭代数据帧并使用基于条件的替换方法
- statistics - 如何将估计每华氏度增加的效应大小转换为摄氏度?
- android - 根据 oAuth2.0 身份验证应该在设备本机浏览器中进行,那么为什么所有已知的应用程序都具有本机登录屏幕
- html - 即使在标记它们之后,边框也不会在 CSS 中显示!重要
- arraylist - 爪哇。将 ListArray 转换为 List
- terraform - 如何在 terraform 中对来自多个来源的资源组 ID 运行 for_each?