SwiftでiOSのバージョン番号を取得するには

Swiftを使ってiOSデバイスのバージョン番号を取得するには、主にUIDeviceクラスのcurrent.systemVersionプロパティと、ProcessInfoクラスのoperatingSystemVersionプロパティの2つの方法があります。

UIDeviceクラスのcurrent.systemVersionプロパティを使用する方法

UIDeviceクラスのcurrent.systemVersionプロパティは、デバイスのOSバージョンを表す文字列を返します。

以下のコードは、iOSのバージョン番号を取得してコンソールに出力します。

let iosVersion = UIDevice.current.systemVersion
print("iOSバージョン: \(iosVersion)") // => iOSバージョン: 17.4

以下は、SwiftUIでiOSのバージョン番号を取得する例です。

import SwiftUI

struct ContentView: View {
    var body: some View {
        Text("iOSバージョン: \(UIDevice.current.systemVersion)") // => iOSバージョン: 17.4
    }
}

ProcessInfoクラスのoperatingSystemVersionプロパティを使用する方法

ProcessInfoのoperatingSystemVersionプロパティは、OSバージョンをmajorVersion、minorVersion、patchVersionの3つの数値で提供します。
これにより、バージョンの各部分を個別に扱うことが可能になります。

以下のコードは、iOSのバージョン番号を取得してコンソールに出力します。

import Foundation

let osVersion = ProcessInfo().operatingSystemVersion
print("Major version: \(osVersion.majorVersion)") // => Major version: 17
print("Minor version: \(osVersion.minorVersion)") // => Minor version: 4
print("Patch version: \(osVersion.patchVersion)") // => Patch version: 0

以下は、SwiftUIでiOSのバージョン番号を取得する例です。

import SwiftUI

struct ContentView: View {
    var body: some View {
        let osVersion = ProcessInfo().operatingSystemVersion
        VStack {
            Text("Major version: \(osVersion.majorVersion)") // => Major version: 17
            Text("Minor version: \(osVersion.minorVersion)") // => Minor version: 4
            Text("Patch version: \(osVersion.patchVersion)") // => Patch version: 0
        }
    }
}

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください