我正在用Swift检查系统信息。我发现,这可以通过代码来实现:
var sysData:CMutablePointer<utsname> = nil
let retVal:CInt = uname(sysData)
这段代码有两个问题:
sysData的初始值应该是什么?这个例子在retVal中给出-1可能是因为sysData为nil。 如何从sysData读取信息?
我正在用Swift检查系统信息。我发现,这可以通过代码来实现:
var sysData:CMutablePointer<utsname> = nil
let retVal:CInt = uname(sysData)
这段代码有两个问题:
sysData的初始值应该是什么?这个例子在retVal中给出-1可能是因为sysData为nil。 如何从sysData读取信息?
当前回答
斯威夫特5
func run() {
let version = OperatingSystemVersion(majorVersion: 13, minorVersion: 0, patchVersion: 0)
if ProcessInfo.processInfo.isOperatingSystemAtLeast(version) {
runNewCode()
} else {
runLegacyCode()
}
}
func runNewCode() {
guard #available(iOS 13.0, *) else {
fatalError()
}
// do new stuff
}
func runLegacyCode() {
// do old stuff
}
其他回答
如果你想查看WatchOS。
斯威夫特
let watchOSVersion = WKInterfaceDevice.currentDevice().systemVersion
print("WatchOS version: \(watchOSVersion)")
objective - c
NSString *watchOSVersion = [[WKInterfaceDevice currentDevice] systemVersion];
NSLog(@"WatchOS version: %@", watchOSVersion);
如果你正在使用Swift 2,并且你想要检查操作系统版本以使用某个API,你可以使用新的可用性特性:
if #available(iOS 8, *) {
//iOS 8+ code here.
}
else {
//Code for iOS 7 and older versions.
//An important note: if you use #availability, Xcode will also
//check that you don't use anything that was introduced in iOS 8+
//inside this `else` block. So, if you try to use UIAlertController
//here, for instance, it won't compile. And it's great.
}
我写这个答案是因为它是谷歌中swift 2 check系统版本查询的第一个问题。
let Device = UIDevice.currentDevice()
let iosVersion = NSString(string: Device.systemVersion).doubleValue
let iOS8 = iosVersion >= 8
let iOS7 = iosVersion >= 7 && iosVersion < 8
检查为
if(iOS8)
{
}
else
{
}
斯威夫特5
我们不需要创建扩展,因为ProcessInfo给了我们版本信息。你可以在下面看到iOS的示例代码。
let os = ProcessInfo().operatingSystemVersion
switch (os.majorVersion, os.minorVersion, os.patchVersion) {
case (let x, _, _) where x < 8:
print("iOS < 8.0.0")
case (8, 0, _):
print("iOS >= 8.0.0, < 8.1.0")
case (8, _, _):
print("iOS >= 8.1.0, < 9.0")
case (9, _, _):
print("iOS >= 9.0.0")
default:
print("iOS >= 10.0.0")
}
参考:http://nshipster.com/swift-system-version-checking/
let osVersion = NSProcessInfo.processInfo().operatingSystemVersion
let versionString = osVersion.majorVersion.description + "." + osVersion.minorVersion.description + "." + osVersion.patchVersion.description
print(versionString)