Objective-C与Swift的转换速查手册

如果你正要从Objective-C过渡到Swift,或反过来,一个在两种语言间显示等效代码的小手册会很有帮助。本文内容就是这些:苹果开发者的红宝书,包含变量,集合,函数,类等等。
下面例子中,上面是Objective-C代码,下面是等效的Swift代码。必要的地方我会给一些备注来帮助你理解。

变量与常量
创建一个变量

//Objective-C
NSInteger score = 556;
//
NSString *name = @"Taylor";
//
BOOL loggedIn = NO;
//Swift
var score = 556
//
var name = "Taylor"
//
var loggedIn = false

创建一个常量

//Objective-C
const NSInteger score = 556;
//
NSString * const name = @"Taylor";
//
const BOOL firstRun = YES;
//Objective-C中常量用的很少
let score = 556
//
let name = "Taylor"
//
let firstRun = true
//Swift中常量很常见

创建一个变量数组



创建一个常量数组

//Objective-C
NSArray *grades = @[@90, @85, @97];
//
NSArray *names = @[@"Taylor", @"Adele", @"Justin"];
//Swift
let grades = [90, 85, 97]
//
let names = ["Taylor", "Adele", "Justin"]

向数组中添加一个值类型

//Objective-C
NSMutableArray *array = [NSMutableArray new];
//
[array addObject:[NSValue valueWithRect:CGRectMake(0, 0, 32, 64)]];
//在添加到集合前,值类型有对应的引用类型
//Swift
var array = [CGRect]()
//
array.append(CGRect(x: 0, y: 0, width: 32, height: 64))

创建一个字典

//Objective-C
NSDictionary *houseNumbers = @{ @"Paul": @7, @"Jess": @56, @"Peter": @332 };
//Swift
let houseNumbers = ["Paul": 7, "Jess": 56, "Peter": 332]

定义一个枚举

//Objective-C
typedef NS_ENUM(NSInteger, ShapeType) {
    kCircle,
    kRectangle,
    kHexagon
};
//Swift
enum ShapeType: Int {
    case circle
    case rectangle
    case hexagon
}

附加一串字符

//Objective-C
NSString *first = @"Hello, ";
NSString *second = [first stringByAppendingString:@" world!"];
//Swift
let first = "Hello, "
let second = first + "world!"

增加数字

//Objective-C
NSInteger rating = 4;
rating++;
rating += 3;
//Swift
var rating = 4
rating += 1
rating += 3

插入字符串

//Objective-C
NSString *account = @"twostraws";
NSString *str = [NSString stringWithFormat:@"Follow me on Twitter: %@", account];
//Swift
let account = "twostraws"
let str = "Follow me on Twitter: \(account)"

打印调试信息

//Objective-C
NSString *username = @"twostraws";
NSLog(@"Username is %@", username);
//Swift
let username = "twostraws"
print("Username is \(username)")

控制流
检查状态

//Objective-C
NSInteger result = 86;

if (result >= 85) {
    NSLog(@"You passed the test!");
} else {
    NSLog(@"Please try again.");
}
//Swift
let result = 86

if result >= 85 {
    print("You passed the test!")
} else {
    print("Please try again.")
}

循环一定次数

//Objective-C
for (NSInteger i = 0; i < 100; ++i) {
    NSLog(@"This will be printed 100 times.");
}
//Swift
for _ in 0 ..< 100 {
    print("This will be printed 100 times.")
}

在数组中循环

//Objective-C
NSArray *companies = @[@"Apple", @"Facebook", @"Twitter"];

for (NSString *name in companies) {
    NSLog(@"%@ is a well-known tech company.", name);
}
//Swift
let companies = ["Apple", "Facebook", "Twitter"]

for name in companies {
    print("\(name) is a well-known tech company.")
}

数值切换

//Objective-C
NSInteger rating = 8;

switch (rating) {
    case 0 ... 3:
        NSLog(@"Awful");
        break;
    case 4 ... 7:
        NSLog(@"OK");
        break;
    case 8 ... 10:
        NSLog(@"Good");
        break;
    default:
        NSLog(@"Invalid rating.");
}
//很多人不知道Objective-C有范围支持,所以你也许看到二选一的语法
//Swift
let rating = 8

switch rating {
case 0...3:
    print("Awful")
case 4...7:
    print("OK")
case 8...10:
    print("Good")
default:
    print("Invalid rating.")
}
//Swift不会fall through案例,除非你使用fallthrough关键字

函数
不接收参数也没有返回的函数

//Objective-C
- (void)printGreeting {
    NSLog(@"Hello!");
}
[self printGreeting];
//Swift
func printGreeting() {
    print("Hello!")
}
printGreeting()

不接收参数,返回一个字符串的函数

//Objective-C
- (NSString*)printGreeting {
    return @"Hello!";
}
NSString *result = [self printGreeting];
//Swift
func printGreeting() -> String {
    return "Hello!"
}
let result = printGreeting()

接收一个字符串,返回一个字符串的函数

//Objective-C
- (NSString*)printGreetingFor:(NSString*)user {
    return [NSString stringWithFormat:@"Hello, %@!", user];
}

NSString *result = [self printGreetingFor:@"Paul"];
//第一个参数的名称需要为方法名的一部分
//Swift
func printGreeting(for user: String) -> String {
    return "Hello, \(user)!"
}

let result = printGreeting(for: "Paul")

接收一个字符串和一个整数,返回一个字符串的函数

//Objective-C
- (NSString*)printGreetingFor:(NSString*)user withAge:(NSInteger)age {
    if (age >= 18) {
        return [NSString stringWithFormat:@"Hello, %@! You're an adult.", user];
    } else {
        return [NSString stringWithFormat:@"Hello, %@! You're a child.", user];
    }
}

NSString *result = [self printGreetingFor:@"Paul" withAge:38];
//Swift
func printGreeting(for user: String, age: Int) -> String {
    if age >= 18 {
        return "Hello, \(user) You're an adult."
    } else {
        return "Hello, \(user)! You're a child."
    }
}

let result = printGreeting(for: "Paul", age: 38)

从函数返回多个值

//Objective-C
- (NSDictionary*)loadAddress {
    return @{
        @"house": @"65, Park Street",
        @"city": @"Bristol",
        @"country": @"UK"
    };
}

NSDictionary*address = [self loadAddress];
NSString *house = address[@"house"];
NSString *city = address[@"city"];
NSString *country = address[@"country"];
//Objective-C不支持元祖(tuple),所以用字典或数组替代
//Swift
func loadAddress() -> (house: String, city: String, country: String) {
    return ("65, Park Street", "Bristol", "UK")
}

let (city, street, country) = loadAddress()

不接收参数没有返回的闭环

//Objective-C
void (^printUniversalGreeting)(void) = ^{
    NSLog(@"Bah-weep-graaaaagnah wheep nini bong");
};

printUniversalGreeting();
//Swift
let universalGreeting = {
    print("Bah-weep-graaaaagnah wheep nini bong")
}

universalGreeting()

不接收参数返回一个字符串的闭环

//Objective-C
NSString* (^getUniversalGreeting)(void) = ^{
    return @"Bah-weep-graaaaagnah wheep nini bong";
};

NSString *greeting = getUniversalGreeting();
NSLog(@"%@", greeting);
//Swift
let getUniversalGreeting = {
    return "Bah-weep-graaaaagnah wheep nini bong"
}

let greeting = getUniversalGreeting()
print(greeting)

接收一个字符串参数,返回一个字符串的闭环

//Objective-C
NSString* (^getGreeting)(NSString *) = ^(NSString *name) {
    return [NSString stringWithFormat:@"Live long and prosper, %@.", name];
};

NSString *greeting = getGreeting(@"Paul");
NSLog(@"%@", greeting);
//Swift
let getGreeting = { (name: String) in
    return "Live long and prosper, \(name)."
}

let greeting = getGreeting("Paul")
print(greeting)


创建空类

//Objective-C
@interface MyClass : NSObject
@end

@implementation MyClass
@end
//Swift
class MyClass: NSObject {
}
//推荐使用结构代替类,这样也许不需要从NSObject继承了

创建有2个属性的类

//Objective-C
@interface User : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSInteger age;
@end

@implementation User

@end
//Swift
class User {
    var name: String
    var age: Int
    
    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
}
//Swift要求进行初始化,给这些属性默认值

创建有一个私有属性的类

//Objective-C
//在头文件中
@interface User : NSObject
@property (nonatomic, copy) NSString *name;
@end

//在执行文件中
@interface User()
@property (nonatomic, assign) NSInteger age;
@end

@implementation User

@end
//Objective-C实际上并不支持私有属性,通常都用这种变通方式
//Swift
class User {
    var name: String
    private var age: Int
    
    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
}

创建有一个实例方法的类

//Objective-C
@interface Civilization : NSObject
- (NSInteger)getMeaningOfLife;
@end

@implementation Civilization
- (NSInteger)getMeaningOfLife {
    return 42;
}
@end
//Swift
class Civilization {
    func getMeaningOfLife() -> Int {
        return 42
    }
}

创建有一个静态方法的类

//Objective-C
@interface Civilization : NSObject
+ (NSInteger)getMeaningOfLife;
@end

@implementation Civilization
+ (NSInteger)getMeaningOfLife {
    return 42;
}
@end
//差别很小,用+而不是-
//Swift
class Civilization {
    class func getMeaningOfLife() -> Int {
        return 42
    }
}
//Swift也支持静态方法——它不会在子类中被覆盖

用一种新方法扩展一个类型

//Objective-C
@interface NSString (Trimming)
- (NSString*)trimmed;
@end

@implementation NSString (Trimming)

- (NSString*)trimmed {
    return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}

@end
//Swift
extension String {
    func trimmed() -> String {
        return trimmingCharacters(in: .whitespacesAndNewlines)
    }
}

检查一个对象的类

//Objective-C
if ([object isKindOfClass:[YourClass class]]) {
    NSLog(@"This is a YourClass.");
}
//Swift
if object is YourClass {
    print("This is a YourClass.")
}

类型转换

//Objective-C
Dog *poodle = (Dog*)animalObject;
//Swift
let poodle = animalObject as? Dog
//
let poodle = animalObject as! Dog
//如果不是一个dog,前者会把poodle设为nil,后者则会崩溃

GCD
在不同线程运行代码

//Objective-C
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSLog(@"Running in the background...");
   
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"Running back on the main thread");
    });
});
//Swift
DispatchQueue.global().async {
    print("Running in the background...")
   
    DispatchQueue.main.async {
        print("Running on the main thread")
    }
}

原文参考链接

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,324评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,303评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,192评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,555评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,569评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,566评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,927评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,583评论 0 257
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,827评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,590评论 2 320
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,669评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,365评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,941评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,928评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,159评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,880评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,399评论 2 342

推荐阅读更多精彩内容