首页 > 解决方案 > 如何比较两个版本

问题描述

我正在尝试比较两个版本的程序,但我无法输入大于 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("вторая версия актуальнее")
}

标签: swift

解决方案


您应该使用数字比较。例如,我想将我的 iOS 版本与 iOS 13 版本进行比较。

let systemVersion = UIDevice.current.systemVersion
if systemVersion.compare("13.0", options: .numeric) != .orderedAscending { 
    // >= 13.0
}

推荐阅读