ios 比较 Swift 中的两个版本字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27932408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 04:20:29  来源:igfitidea点击:

Compare two version strings in Swift

iosswift

提问by codeman

I have two different app version Strings (i.e. "3.0.1" and "3.0.2").

我有两个不同的应用程序版本字符串(即“3.0.1”和“3.0.2”)。

How can compare these using Swift?

如何使用Swift比较这些?

回答by codeman

Ended up having to convert my Strings to NSStrings:

最终不得不将我的字符串转换为 NSStrings:

if storeVersion.compare(currentVersion, options: NSStringCompareOptions.NumericSearch) == NSComparisonResult.OrderedDescending {
       println("store version is newer")
}

Swift 3

斯威夫特 3

let currentVersion = "3.0.1"
let storeVersion = "3.0.2"

if storeVersion.compare(currentVersion, options: .numeric) == .orderedDescending {
    print("store version is newer")
}

回答by DragonCherry

You don't need to cast it as NSString. String object in Swift 3 is just powerful enough to compare versions like below.

您不需要将其转换为 NSString。Swift 3 中的 String 对象足够强大,可以比较如下版本。

let version = "1.0.0"
let targetVersion = "0.5.0"

version.compare(targetVersion, options: .numeric) == .orderedSame        // false
version.compare(targetVersion, options: .numeric) == .orderedAscending   // false
version.compare(targetVersion, options: .numeric) == .orderedDescending  // true

But sample above does not cover versions with extra zeros.(Ex: "1.0.0" & "1.0")

但是上面的示例不包括带有额外零的版本。(例如:“1.0.0”和“1.0”)

So, I've made all kinds of these extension methods in String to handle version comparison using Swift. It does consider extra zeros I said, quite simple and will work as you expected.

因此,我在 String 中创建了各种这些扩展方法来使用 Swift 处理版本比较。它确实考虑了我说的额外零,非常简单,并且会按您的预期工作。

XCTAssertTrue(UIDevice.current.systemVersion.isVersion(lessThan: "99.0.0"))
XCTAssertTrue(UIDevice.current.systemVersion.isVersion(equalTo: UIDevice.current.systemVersion))
XCTAssertTrue(UIDevice.current.systemVersion.isVersion(greaterThan: "3.5.99"))
XCTAssertTrue(UIDevice.current.systemVersion.isVersion(lessThanOrEqualTo: "13.5.99"))
XCTAssertTrue(UIDevice.current.systemVersion.isVersion(greaterThanOrEqualTo: UIDevice.current.systemVersion))
XCTAssertTrue("0.1.1".isVersion(greaterThan: "0.1"))
XCTAssertTrue("0.1.0".isVersion(equalTo: "0.1"))
XCTAssertTrue("10.0.0".isVersion(equalTo: "10"))
XCTAssertTrue("10.0.1".isVersion(equalTo: "10.0.1"))
XCTAssertTrue("5.10.10".isVersion(lessThan: "5.11.5"))
XCTAssertTrue("1.0.0".isVersion(greaterThan: "0.99.100"))
XCTAssertTrue("0.5.3".isVersion(lessThanOrEqualTo: "1.0.0"))
XCTAssertTrue("0.5.29".isVersion(greaterThanOrEqualTo: "0.5.3"))

Just take a look and take all you want in my sample extension repository with no license to care about.

只需在我的示例扩展存储库中查看并获取您想要的所有内容,无需关心任何许可证。

https://github.com/DragonCherry/VersionCompare

https://github.com/DragonCherry/VersionCompare

回答by Wane

Swift 3 version

斯威夫特 3 版本

let storeVersion = "3.14.10"
let currentVersion = "3.130.10"

extension String {
    func versionToInt() -> [Int] {
        return self.components(separatedBy: ".")
            .map { Int.init(
let storeVersion = "3.14.10"

let currentVersion = "3.130.10"
extension String {
    func versionToInt() -> [Int] {
      return self.componentsSeparatedByString(".")
          .map {
              Int.init(
extension String {

  static func ==(lhs: String, rhs: String) -> Bool {
    return lhs.compare(rhs, options: .numeric) == .orderedSame
  }

  static func <(lhs: String, rhs: String) -> Bool {
    return lhs.compare(rhs, options: .numeric) == .orderedAscending
  }

  static func <=(lhs: String, rhs: String) -> Bool {
    return lhs.compare(rhs, options: .numeric) == .orderedAscending || lhs.compare(rhs, options: .numeric) == .orderedSame
  }

  static func >(lhs: String, rhs: String) -> Bool {
    return lhs.compare(rhs, options: .numeric) == .orderedDescending
  }

  static func >=(lhs: String, rhs: String) -> Bool {
    return lhs.compare(rhs, options: .numeric) == .orderedDescending || lhs.compare(rhs, options: .numeric) == .orderedSame
  }

}


"1.2.3" == "1.2.3" // true
"1.2.3" > "1.2.3" // false
"1.2.3" >= "1.2.3" // true
"1.2.3" < "1.2.3" // false
"1.2.3" <= "1.2.3" // true

"3.0.0" >= "3.0.0.1" // false
"3.0.0" > "3.0.0.1" // false
"3.0.0" <= "3.0.0.1" // true
"3.0.0.1" >= "3.0.0.1" // true
"3.0.1.1.1.1" >= "3.0.2" // false
"3.0.15" > "3.0.1.1.1.1" // true
"3.0.10" > "3.0.100.1.1.1" // false
"3.0.1.1.1.3.1.7" == "3.0.1.1.1.3.1" // false
"3.0.1.1.1.3.1.7" > "3.0.1.1.1.3.1" // true

"3.14.10" == "3.130.10" // false
"3.14.10" > "3.130.10" // false
"3.14.10" >= "3.130.10" // false
"3.14.10" < "3.130.10" // true
"3.14.10" <= "3.130.10" // true
) ?? 0 } } } // true storeVersion.versionToInt().lexicographicalCompare(currentVersion.versionToInt())
) ?? 0 } } } //true storeVersion.versionToInt().lexicographicallyPrecedes(currentVersion.versionToInt())

Swift 2 version compare

Swift 2 版本比较

let current = "1.3"
let appStore = "1.2.9"
let versionCompare = current.compare(appStore, options: .numeric)
if versionCompare == .orderedSame {
    print("same version")
} else if versionCompare == .orderedAscending {
    // will execute the code here
    print("ask user to update")
} else if versionCompare == .orderedDescending {
    // execute if current > appStore
    print("don't expect happen...")
}

回答by Ashok

The following is working for me:

以下对我有用:

func ascendingOrSameVersion(minorVersion smallerVersion:String, largerVersion:String)->Bool{
    var result = true //default value is equal

    let smaller = split(smallerVersion){ 
print("2.0.3".compare("2.0.4", options: .numeric))//orderedAscending
print("2.0.3".compare("2.0.5", options: .numeric))//orderedAscending

print("2.0.4".compare("2.0.4", options: .numeric))//orderedSame

print("2.0.4".compare("2.0.3", options: .numeric))//orderedDescending
print("2.0.5".compare("2.0.3", options: .numeric))//orderedDescending

print("2.0.10".compare("2.0.11", options: .numeric))//orderedAscending
print("2.0.10".compare("2.0.20", options: .numeric))//orderedAscending

print("2.0.0".compare("2.0.00", options: .numeric))//orderedSame
print("2.0.00".compare("2.0.0", options: .numeric))//orderedSame

print("2.0.20".compare("2.0.19", options: .numeric))//orderedDescending
print("2.0.99".compare("2.1.0", options: .numeric))//orderedAscending
== "." } let larger = split(largerVersion){
"1.1.2".compare("1.1.1").rawValue -> ComparisonResult.orderedDescending
"1.1.2".compare("1.1.2").rawValue -> ComparisonResult.orderedSame
"1.1.2".compare("1.1.3").rawValue -> ComparisonResult.orderedAscending
== "." } let maxLength = max(smaller.count, larger.count) for var i:Int = 0; i < maxLength; i++ { var s = i < smaller.count ? smaller[i] : "0" var l = i < larger.count ? larger[i] : "0" if s != l { result = s < l break } } return result }

enter image description here

在此处输入图片说明

回答by PinkeshGjr

Swift 4

斯威夫特 4

class VersionString: NSObject {

    // MARK: - Properties
    var string = ""
    override var description: String {
        return string
    }

    // MARK: - Initialization
    private override init() {
        super.init()
    }
    convenience init(_ string: String) {
        self.init()
        self.string = string
    }

    func compare(_ rhs: VersionString) -> ComparisonResult {
        return string.compare(rhs.string, options: .numeric)
    }

    static func ==(lhs: VersionString, rhs: VersionString) -> Bool {
        return lhs.compare(rhs) == .orderedSame
    }

    static func <(lhs: VersionString, rhs: VersionString) -> Bool {
        return lhs.compare(rhs) == .orderedAscending
    }

    static func <=(lhs: VersionString, rhs: VersionString) -> Bool {
        return lhs.compare(rhs) == .orderedAscending || lhs.compare(rhs) == .orderedSame
    }

    static func >(lhs: VersionString, rhs: VersionString) -> Bool {
        return lhs.compare(rhs) == .orderedDescending
    }

    static func >=(lhs: VersionString, rhs: VersionString) -> Bool {
        return lhs.compare(rhs) == .orderedDescending || lhs.compare(rhs) == .orderedSame
    }
}

let v1 = VersionString("1.2.3")
let v2 = VersionString("1.2.3")

print("\(v1) == \(v2): \(v1 == v2)") // 1.2.3 == 1.2.3: true
print("\(v1) >  \(v2): \(v1 > v2)")  // 1.2.3 >  1.2.3: false
print("\(v1) >= \(v2): \(v1 >= v2)") // 1.2.3 >= 1.2.3: true
print("\(v1) <  \(v2): \(v1 < v2)")  // 1.2.3 <  1.2.3: false
print("\(v1) <= \(v2): \(v1 <= v2)") // 1.2.3 <= 1.2.3: true

回答by HamGuy

Sometimes, the storeVersion's length is not equal to the currentVersion's. e.g. maybe storeVersion is 3.0.0, however, you fixed a bug and named it 3.0.0.1.

有时,storeVersion 的长度不等于 currentVersion 的长度。例如,也许 storeVersion 是3.0.0,但是,您修复了一个错误并将其命名为3.0.0.1

##代码##

回答by computingfreak

Using Swift 3, application version strings can be compare using the compare function with the option set to numeric.

使用 Swift 3,可以使用将选项设置为数字的 compare 函数来比较应用程序版本字符串。

read this String Programming Guide from Apple Developers' documentationfor Objective-C examples of how it works.

阅读Apple Developers 文档中的 String Programming Guide,以获取有关其工作原理的 Objective-C 示例。

i tried these at https://iswift.org/playground

我在https://iswift.org/playground尝试了这些

##代码##

Hope that helps!

希望有帮助!

If you like using libraries, use this one, don't reinvent the wheel. https://github.com/zenangst/Versions

如果您喜欢使用库,请使用此库,不要重新发明轮子。 https://github.com/zenangst/Versions

回答by Konstantine Dementiev

You can do it using 'String.compare' method. Use ComparisonResult to identify when your version greater, equal or less.

您可以使用“String.compare”方法来完成。使用比较结果来确定您的版本何时大于、等于或小于。

Example:

例子:

##代码##

回答by Alex Koshy

Wrote a small Swift 3 class to do this:

写了一个小的 Swift 3 类来做到这一点:

##代码##

回答by Endy Silveira

@DragonCherry solution is great!

@DragonCherry 解决方案很棒!

But, unfortunately, it doesn't work when the version is like 1.0.1.2(I know, it shouldn't exist, but things happens).

但是,不幸的是,当版本是这样时它不起作用1.0.1.2(我知道,它不应该存在,但事情发生了)。

I changed your extension and improved the tests to cover (I believe) all cases. Also, I created an extension that removes all the unnecessary characters from the version string, sometimes it can be v1.0.1.2.

我更改了您的扩展并改进了测试以涵盖(我相信)所有情况。此外,我创建了一个扩展,从版本字符串中删除所有不必要的字符,有时它可以是v1.0.1.2.

You can check all the code in the following gists:

您可以检查以下要点中的所有代码:

Hope it helps anyone :)

希望它可以帮助任何人:)