1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Swift】バージョンを比較したい

Last updated at Posted at 2023-11-01

はじめに

「バージョンアップしてください」的なアラートを出す際に、現在使用しているバージョンとストアにある最新バージョンを比較するという作業が必要です。
バージョンできるようにするための構造体を作成しましたので記録しておきます。

注意
セマンティックバージョニングのみ対応してます

実装

SemanticVersion.swift
import Foundation

public struct SemanticVersion {
    public let major: Int
    public let minor: Int
    public let patch: Int

    public init(_ major: Int, _ minor: Int, _ patch: Int) {
        self.major = major
        self.minor = minor
        self.patch = patch
    }

    public init?(_ string: String) {
        let pattern = #"([0-9]+)\.([0-9]+)\.([0-9]+)"#
        let versions = string.match(pattern)
            .compactMap(Int.init)
        guard versions.count == 3 else { return nil }

        self.major = versions[0]
        self.minor = versions[1]
        self.patch = versions[2]
    }
}

extension SemanticVersion: CustomStringConvertible {
    public var description: String {
        "\(major).\(minor).\(patch)"
    }
}

extension SemanticVersion: Comparable {
    public static func < (lhs: SemanticVersion, rhs: SemanticVersion) -> Bool {
        (lhs.major, lhs.minor, lhs.patch) < (rhs.major, rhs.minor, rhs.patch)
    }
}
String+match.swift
import Foundation

public extension String {
    func match(_ pattern: String) -> [String] {
        guard let regex = try? NSRegularExpression(pattern: pattern),
              let matched = regex.firstMatch(in: self, range: NSRange(location: 0, length: self.count))
        else { return [] }
        return (0 ..< matched.numberOfRanges).map {
            NSString(string: self).substring(with: matched.range(at: $0))
        }
    }
}

使い方1

let version1: SemanticVersion = .init(1, 0, 0)
let version2: SemanticVersion = .init(1, 0, 1)

print(version1 < version2)

使い方2

let version1: SemanticVersion = .init("1.0.0")!
let version2: SemanticVersion = .init("1.0.1")!

print(version1 < version2)

おわり

これで比較できるようになりました!

1
4
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?