我有两个不同的应用版本字符串(即" 3.0.1"和" 3.0.2")。
如何使用 Swift 进行比较?
答案 0 :(得分:98)
结束必须将我的字符串转换为NSStrings:
if storeVersion.compare(currentVersion, options: NSStringCompareOptions.NumericSearch) == NSComparisonResult.OrderedDescending {
println("store version is newer")
}
Swift 3
let currentVersion = "3.0.1"
let storeVersion = "3.0.2"
if storeVersion.compare(currentVersion, options: .numeric) == .orderedDescending {
print("store version is newer")
}
答案 1 :(得分:25)
您不需要将其强制转换为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
但上面的示例并未涵盖带有额外零的版本。(例如:“1.0.0”&“1.0”)
所以,我在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"))
只需查看并在我的示例扩展存储库中获取您想要的所有内容,无需关心许可。
答案 2 :(得分:19)
Swift 3版
let storeVersion = "3.14.10"
let currentVersion = "3.130.10"
extension String {
func versionToInt() -> [Int] {
return self.components(separatedBy: ".")
.map { Int.init($0) ?? 0 }
}
}
//true
storeVersion.versionToInt().lexicographicallyPrecedes(currentVersion.versionToInt())
Swift 2版本比较
let storeVersion = "3.14.10"
let currentVersion = "3.130.10"
extension String {
func versionToInt() -> [Int] {
return self.componentsSeparatedByString(".")
.map {
Int.init($0) ?? 0
}
}
}
// true
storeVersion.versionToInt().lexicographicalCompare(currentVersion.versionToInt())
答案 3 :(得分:9)
以下内容对我有用:
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
答案 4 :(得分:3)
有时,storeVersion的长度不等于currentVersion的长度。例如也许storeVersion是3.0.0
,但是,您修复了一个错误并将其命名为3.0.0.1
。
func ascendingOrSameVersion(minorVersion smallerVersion:String, largerVersion:String)->Bool{
var result = true //default value is equal
let smaller = split(smallerVersion){ $0 == "." }
let larger = split(largerVersion){ $0 == "." }
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
}
答案 5 :(得分:2)
使用Swift 3,可以使用比较功能和选项设置为数字来比较应用程序版本字符串。
阅读this String Programming Guide from Apple Developers' documentation了解Objective-C的工作原理示例。
我在https://iswift.org/playground
尝试了这些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
希望有所帮助!
如果您喜欢使用库,请使用此库,不要重新发明轮子。 https://github.com/zenangst/Versions
答案 6 :(得分:2)
你可以使用&#39; String.compare&#39;方法。 使用ComparisonResult来识别您的版本何时更大,相等或更小。
示例:
"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
答案 7 :(得分:2)
写了一个小的Swift 3类来做这个:
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
答案 8 :(得分:1)
我最终为我的项目创建了以下类。在这里分享,以防它对某人有帮助。干杯……!!
import Foundation
final class AppVersionComparator {
var currentVersion: String
init() {
let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
self.currentVersion = version ?? ""
}
func compareVersions(lhs: String, rhs: String) -> ComparisonResult {
let comparisonResult = lhs.compare(rhs, options: .numeric)
return comparisonResult
}
/**
- If lower bound is present perform lowerBound check
- If upper bound is present perform upperBound check
- Return true if both are nil
*/
func fallsInClosedRange(lowerBound: String?, upperBound: String?) -> Bool {
if let lowerBound = lowerBound {
let lowerBoundComparisonResult = compareVersions(lhs: currentVersion, rhs: lowerBound)
guard lowerBoundComparisonResult == .orderedSame || lowerBoundComparisonResult == .orderedDescending else { return false }
}
if let upperBound = upperBound {
let upperBoundComparisonResult = compareVersions(lhs: currentVersion, rhs: upperBound)
guard upperBoundComparisonResult == .orderedSame || upperBoundComparisonResult == .orderedAscending else { return false }
}
return true
}
/**
- If lower bound is present perform lowerBound check
- If upper bound is present perform upperBound check
- Return true if both are nil
*/
func fallsInOpenRange(lowerBound: String?, upperBound: String?) -> Bool {
if let lowerBound = lowerBound {
let lowerBoundComparisonResult = compareVersions(lhs: currentVersion, rhs: lowerBound)
guard lowerBoundComparisonResult == .orderedDescending else { return false }
}
if let upperBound = upperBound {
let upperBoundComparisonResult = compareVersions(lhs: currentVersion, rhs: upperBound)
guard upperBoundComparisonResult == .orderedAscending else { return false }
}
return true
}
func isCurrentVersionGreaterThan(version: String) -> Bool {
let result = compareVersions(lhs: currentVersion, rhs: version)
return result == .orderedDescending
}
func isCurrentVersionLessThan(version: String) -> Bool {
let result = compareVersions(lhs: currentVersion, rhs: version)
return result == .orderedAscending
}
func isCurrentVersionEqualsTo(version: String) -> Bool {
let result = compareVersions(lhs: currentVersion, rhs: version)
return result == .orderedSame
}}
还有一些测试用例:
import XCTest
class AppVersionComparatorTests: XCTestCase {
var appVersionComparator: AppVersionComparator!
override func setUp() {
super.setUp()
self.appVersionComparator = AppVersionComparator()
}
func testInit() {
XCTAssertFalse(appVersionComparator.currentVersion.isEmpty)
}
func testCompareEqualVersions() {
let testVersions = [VersionComparisonModel(lhs: "1.2.1", rhs: "1.2.1"),
VersionComparisonModel(lhs: "1.0", rhs: "1.0"),
VersionComparisonModel(lhs: "1.0.2", rhs: "1.0.2"),
VersionComparisonModel(lhs: "0.1.1", rhs: "0.1.1"),
VersionComparisonModel(lhs: "3.2.1", rhs: "3.2.1")]
for model in testVersions {
let result = appVersionComparator.compareVersions(lhs: model.lhs, rhs: model.rhs)
XCTAssertEqual(result, .orderedSame)
}
}
func testLHSLessThanRHS() {
let lhs = "1.2.0"
let rhs = "1.2.1"
let result = appVersionComparator.compareVersions(lhs: lhs, rhs: rhs)
XCTAssertEqual(result, .orderedAscending)
}
func testInvalidRange() {
let isCurrentVersionInClosedRange = appVersionComparator.fallsInClosedRange(lowerBound: "", upperBound: "")
XCTAssertFalse(isCurrentVersionInClosedRange)
let isCurrentVersionInOpenRange = appVersionComparator.fallsInOpenRange(lowerBound: "", upperBound: "")
XCTAssertFalse(isCurrentVersionInOpenRange)
}
func testCurrentInClosedRangeSuccess() {
appVersionComparator.currentVersion = "1.2.1"
let isCurrentVersionInClosedRange = appVersionComparator.fallsInClosedRange(lowerBound: "1.2.0", upperBound: "1.2.1")
XCTAssert(isCurrentVersionInClosedRange)
}
func testIsCurrentVersionGreaterThanGivenVersion() {
appVersionComparator.currentVersion = "1.4.2"
let result = appVersionComparator.isCurrentVersionGreaterThan(version: "1.2")
XCTAssert(result)
}
func testIsCurrentVersionLessThanGivenVersion() {
appVersionComparator.currentVersion = "1.4.2"
let result = appVersionComparator.isCurrentVersionLessThan(version: "1.5")
XCTAssert(result)
}
func testIsCurrentVersionEqualsToGivenVersion() {
appVersionComparator.currentVersion = "1.4.2"
let result = appVersionComparator.isCurrentVersionEqualsTo(version: "1.4.2")
XCTAssert(result)
}}
Mock Model:
struct VersionComparisonModel {
let lhs: String
let rhs: String
}
答案 9 :(得分:1)
快捷键4
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...")
}
答案 10 :(得分:1)
您使用NSString
是正确的方法,但这是非基金会的尝试:
let storeVersion = "3.14.10"
let currentVersion = "3.130.10"
func versionToArray(version: String) -> [Int] {
return split(version) {
$0 == "."
}.map {
// possibly smarter ways to do this
$0.toInt() ?? 0
}
}
storeVersion < currentVersion // false
// true
lexicographicalCompare(versionToArray(storeVersion), versionToArray(currentVersion))
答案 11 :(得分:0)
如何?
class func compareVersion(_ ver: String, to toVer: String) -> ComparisonResult {
var ary0 = ver.components(separatedBy: ".").map({ return Int($0) ?? 0 })
var ary1 = toVer.components(separatedBy: ".").map({ return Int($0) ?? 0 })
while ary0.count < 3 {
ary0.append(0)
}
while ary1.count < 3 {
ary1.append(0)
}
let des0 = ary0[0...2].description
let des1 = ary1[0...2].description
return des0.compare(des1, options: .numeric)
}
并测试:
func test_compare_version() {
XCTAssertEqual(compareVersion("1.0.0", to: "1.0.0"), .orderedSame)
XCTAssertEqual(compareVersion("1.0.0", to: "1.0."), .orderedSame)
XCTAssertEqual(compareVersion("1.0.0", to: "1.0"), .orderedSame)
XCTAssertEqual(compareVersion("1.0.0", to: "1."), .orderedSame)
XCTAssertEqual(compareVersion("1.0.0", to: "1"), .orderedSame)
XCTAssertEqual(compareVersion("1.0.0", to: "1.0.1"), .orderedAscending)
XCTAssertEqual(compareVersion("1.0.0", to: "1.1."), .orderedAscending)
XCTAssertEqual(compareVersion("1.0.0", to: "1.1"), .orderedAscending)
XCTAssertEqual(compareVersion("1.0.0", to: "2."), .orderedAscending)
XCTAssertEqual(compareVersion("1.0.0", to: "2"), .orderedAscending)
XCTAssertEqual(compareVersion("1.0.0", to: "1.0.0"), .orderedSame)
XCTAssertEqual(compareVersion("1.0.", to: "1.0.0"), .orderedSame)
XCTAssertEqual(compareVersion("1.0", to: "1.0.0"), .orderedSame)
XCTAssertEqual(compareVersion("1.", to: "1.0.0"), .orderedSame)
XCTAssertEqual(compareVersion("1", to: "1.0.0"), .orderedSame)
XCTAssertEqual(compareVersion("1.0.1", to: "1.0.0"), .orderedDescending)
XCTAssertEqual(compareVersion("1.1.", to: "1.0.0"), .orderedDescending)
XCTAssertEqual(compareVersion("1.1", to: "1.0.0"), .orderedDescending)
XCTAssertEqual(compareVersion("2.", to: "1.0.0"), .orderedDescending)
XCTAssertEqual(compareVersion("2", to: "1.0.0"), .orderedDescending)
XCTAssertEqual(compareVersion("1.0.0", to: "0.9.9"), .orderedDescending)
XCTAssertEqual(compareVersion("1.0.0", to: "0.9."), .orderedDescending)
XCTAssertEqual(compareVersion("1.0.0", to: "0.9"), .orderedDescending)
XCTAssertEqual(compareVersion("1.0.0", to: "0."), .orderedDescending)
XCTAssertEqual(compareVersion("1.0.0", to: "0"), .orderedDescending)
XCTAssertEqual(compareVersion("", to: "0"), .orderedSame)
XCTAssertEqual(compareVersion("0", to: ""), .orderedSame)
XCTAssertEqual(compareVersion("", to: "1"), .orderedAscending)
XCTAssertEqual(compareVersion("1", to: ""), .orderedDescending)
XCTAssertEqual(compareVersion("1.0.0", to: "1.0.0.9"), .orderedSame)
XCTAssertEqual(compareVersion("1.0.0.9", to: "1.0.0"), .orderedSame)
}
答案 12 :(得分:0)
这是一个简单的swift结构
public struct VersionString: Comparable {
public let rawValue: String
public init(_ rawValue: String) {
self.rawValue = rawValue
}
public static func == (lhs: VersionString, rhs: VersionString) -> Bool {
return lhs.rawValue.compare(rhs.rawValue, options: .numeric) == .orderedSame
}
public static func < (lhs: VersionString, rhs: VersionString) -> Bool {
return lhs.rawValue.compare(rhs.rawValue, options: .numeric) == .orderedAscending
}
}
答案 13 :(得分:0)
@DragonCherry解决方案很棒!
但是,不幸的是,当版本为1.0.1.2
时,它不起作用(我知道,它应该存在,但是事情确实发生了。)
我更改了您的扩展名,并改进了测试以涵盖(我认为)所有情况。
另外,我创建了一个扩展程序,该扩展程序从版本字符串中删除了所有不必要的字符,有时可以是v1.0.1.2
。
您可以检查以下要点中的所有代码:
希望它对任何人都有帮助:)
答案 14 :(得分:0)
我混合了Ashok版本和DragonCherry版本:
// MARK: - Version comparison
extension String {
// Modified from the DragonCherry extension - https://github.com/DragonCherry/VersionCompare
private func compare(toVersion targetVersion: String) -> ComparisonResult {
let versionDelimiter = "."
var result: ComparisonResult = .orderedSame
var versionComponents = components(separatedBy: versionDelimiter)
var targetComponents = targetVersion.components(separatedBy: versionDelimiter)
while versionComponents.count < targetComponents.count {
versionComponents.append("0")
}
while targetComponents.count < versionComponents.count {
targetComponents.append("0")
}
for (version, target) in zip(versionComponents, targetComponents) {
result = version.compare(target, options: .numeric)
if result != .orderedSame {
break
}
}
return result
}
func isVersion(equalTo targetVersion: String) -> Bool { return compare(toVersion: targetVersion) == .orderedSame }
func isVersion(greaterThan targetVersion: String) -> Bool { return compare(toVersion: targetVersion) == .orderedDescending }
func isVersion(greaterThanOrEqualTo targetVersion: String) -> Bool { return compare(toVersion: targetVersion) != .orderedAscending }
func isVersion(lessThan targetVersion: String) -> Bool { return compare(toVersion: targetVersion) == .orderedAscending }
func isVersion(lessThanOrEqualTo targetVersion: String) -> Bool { return compare(toVersion: targetVersion) != .orderedDescending }
static func ==(lhs: String, rhs: String) -> Bool { lhs.compare(toVersion: rhs) == .orderedSame }
static func <(lhs: String, rhs: String) -> Bool { lhs.compare(toVersion: rhs) == .orderedAscending }
static func <=(lhs: String, rhs: String) -> Bool { lhs.compare(toVersion: rhs) != .orderedDescending }
static func >(lhs: String, rhs: String) -> Bool { lhs.compare(toVersion: rhs) == .orderedDescending }
static func >=(lhs: String, rhs: String) -> Bool { lhs.compare(toVersion: rhs) != .orderedAscending }
}
使用:
"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.1.1".isVersion(greaterThan: "0.1")
"0.1.0".isVersion(equalTo: "0.1")
"10.0.0".isVersion(equalTo: "10")
"10.0.1".isVersion(equalTo: "10.0.1")
"5.10.10".isVersion(lessThan: "5.11.5")
"1.0.0".isVersion(greaterThan: "0.99.100")
"0.5.3".isVersion(lessThanOrEqualTo: "1.0.0")
"0.5.29".isVersion(greaterThanOrEqualTo: "0.5.3")
答案 15 :(得分:0)
我可以理解,这里给出了许多很好的答案。这是我对应用程序版本进行比较的版本。
func compareVersions(installVersion: String, storeVersion: String) -> Bool{
// 1.7.5
var installedArr = installVersion.components(separatedBy: ".")
var storeArr = storeVersion.components(separatedBy: ".")
var isAvailable = false
while(installedArr.count < storeArr.count){
installedArr.append("0")
}
while(storeArr.count < installedArr.count){
storeArr.append("0")
}
for index in 0 ..< installedArr.count{
if let storeIndex=storeArr[index].toInt(), let installIndex=installedArr[index].toInt(){
if storeIndex > installIndex{
isAvailable = true
return isAvailable
}
}
}
return isAvailable
}
答案 16 :(得分:0)
我将尽力涵盖所有版本格式的案例,例如将"10.0"
与"10.0.1"
进行比较,让我知道是否遗漏了任何案例。
这里是要点https://gist.github.com/shamzahasan88/bc22af2b7c96b6a06a064243a02c8bcc。希望对大家有帮助。
如果有人不想对我的要点进行评分,则这里是代码:P
extension String {
// Version format "12.34.39" where "12" is "Major", "34" is "Minor" and "39" is "Bug fixes"
// "maximumDigitCountInVersionComponent" is optional parameter determines the maximum length of "Maajor", "Minor" and "Bug Fixes"
func shouldUpdateAsCompareToVersion(storeVersion: String, maximumDigitCountInVersionComponent: Int = 5) -> Bool {
let adjustTralingZeros: (String, Int)->String = { val, count in
return "\(val)\((0..<(count)).map{_ in "0"}.joined(separator: ""))"
}
let adjustLength: ([String.SubSequence], Int)->[String] = { strArray, count in
return strArray.map {adjustTralingZeros("\($0)", count-$0.count)}
}
let storeVersionSubSequence = storeVersion.split(separator: ".")
let currentVersionSubSequence = self.split(separator: ".")
let formatter = NumberFormatter()
formatter.minimumIntegerDigits = maximumDigitCountInVersionComponent
formatter.maximumIntegerDigits = maximumDigitCountInVersionComponent
let storeVersions = adjustLength(storeVersionSubSequence, maximumDigitCountInVersionComponent)
let currentVersions = adjustLength(currentVersionSubSequence, maximumDigitCountInVersionComponent)
var storeVersionString = storeVersions.joined(separator: "")
var currentVersionString = currentVersions.joined(separator: "")
let diff = storeVersionString.count - currentVersionString.count
if diff > 0 {
currentVersionString = adjustTralingZeros(currentVersionString, diff)
}else if diff < 0 {
storeVersionString = adjustTralingZeros(storeVersionString, -diff)
}
let literalStoreVersion = Int(storeVersionString)!
let literalCurrentVersion = Int(currentVersionString)!
return literalCurrentVersion < literalStoreVersion
}
}
用法:
print("33.29".shouldUpdateAsCompareToVersion(storeVersion: "34.23.19")) // true
print("35.29".shouldUpdateAsCompareToVersion(storeVersion: "34.23.19")) // false
print("34.23.2".shouldUpdateAsCompareToVersion(storeVersion: "34.23.19")) // false
print("34.23.18".shouldUpdateAsCompareToVersion(storeVersion: "34.23.19")) // true
答案 17 :(得分:0)
extension String {
func compareVersionNumbers(other: String) -> Int {
let nums1 = self.split(separator: ".").map({ Int($0) ?? 0 })
let nums2 = other.split(separator: ".").map({ Int($0) ?? 0 })
for i in 0..<max(nums1.count, nums2.count) {
let num1 = i < nums1.count ? nums1[i] : 0
let num2 = i < nums2.count ? nums2[i] : 0
if num1 != num2 {
return num1 - num2
}
}
return 0
}
}
答案 18 :(得分:0)
extension String {
func versionCompare(_ otherVersion: String) -> ComparisonResult {
let versionDelimiter = "."
var versionComponents = self.components(separatedBy: versionDelimiter) // <1>
var otherVersionComponents = otherVersion.components(separatedBy: versionDelimiter)
let zeroDiff = versionComponents.count - otherVersionComponents.count // <2>
if zeroDiff == 0 { // <3>
// Same format, compare normally
return self.compare(otherVersion, options: .literal)
} else {
let zeros = Array(repeating: "0", count: abs(zeroDiff)) // <4>
if zeroDiff > 0 {
otherVersionComponents.append(contentsOf: zeros) // <5>
} else {
versionComponents.append(contentsOf: zeros)
}
return versionComponents.joined(separator: versionDelimiter)
.compare(otherVersionComponents.joined(separator: versionDelimiter), options: .literal) // <6>
}
}
}
//用法
let previousVersionNumber = "1.102.130"
let newAnpStoreVersion = "1.2" // <- Higher
switch previousVersionNumber.versionCompare(newAnpStoreVersion) {
case .orderedAscending:
case .orderedSame:
case .orderedDescending:
}