Last active
July 7, 2020 08:22
-
-
Save shamzahasan88/bc22af2b7c96b6a06a064243a02c8bcc to your computer and use it in GitHub Desktop.
Custom String extension of Swift to compare versions in String.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension String { | |
// Compare iOS version in Swift | |
// 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 "Major", "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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment