iOS Swift 版本比较大小

2020-12-10  本文已影响0人  乡下秋草

思路:

将版本号字符串根据.分割成数组,再遍历比较第一位,第二位……直到判断出版本号大小来。

func compareVersion(nowVersion:String,newVersion:String) -> Bool {
        
        let nowArray = nowVersion.split(separator: ".")
        
        let newArray = newVersion.split(separator: ".")
        
        let big = nowArray.count > newArray.count ? newArray.count : nowArray.count
        
        for index in 0...big - 1 {
            
            let first = nowArray[index]
            let second = newArray[index]
            if Int(first)! < Int(second)!  {
                return true
            }
        }
        return false
    }

调用

let newVersion =  self.compareVersion(nowVersion: "1.1.12", newVersion: "1.2.2")
        
        if newVersion {
            print("新版本")
        }
上一篇 下一篇

猜你喜欢

热点阅读