You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Objective-C的UIDevice+SystemVersion分类转换为Swift?

Objective-C的UIDevice分类转Swift实现

原Objective-C代码

头文件(.h)

#import <UIKit/UIKit.h>

@interface UIDevice(SystemVersion)

- (BOOL)systemVersionLessThan:(NSString *)target;

@end

实现文件(.m)

#import "UIDevice+SystemVersion.h"

@implementation UIDevice(SystemVersion)

- (BOOL)systemVersionLessThan:(NSString *)target {
    return [[self systemVersion] compare:target options:NSNumericSearch] == NSOrderedAscending;
}

@end

用户尝试的错误Swift代码

import UIKit

extension UIDevice {
  func SystemVersion() {
    if systemVersionLessThan ->  {}
  }
}

正确的Swift实现

import UIKit

extension UIDevice {
    func systemVersionLessThan(_ target: String) -> Bool {
        return systemVersion.compare(target, options: .numeric) == .orderedAscending
    }
}

关键说明

  • Swift用extension实现类扩展,对应Objective-C的分类功能
  • 参数前的_用于省略调用时的外部参数名,保持和Objective-C一致的调用体验(例如UIDevice.current.systemVersionLessThan("15.0"))
  • .numeric对应Objective-C的NSNumericSearch,.orderedAscending对应NSOrderedAscending,Swift采用枚举简写形式
  • 直接返回版本比较结果,逻辑和原Objective-C代码完全一致

内容的提问来源于stack exchange,提问作者MarisLakss

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 07:01:14