前言
如果你正要從Objective-C過渡到Swift,或反過來,一個在兩種語言間顯示等效代碼的小手冊會很有幫助。本文內容就是這些:蘋果開發者的紅寶書,包含變量,集合,函數,類等等。
下面例子中,上面是Objective-C代碼,下面是等效的Swift代碼。必要的地方我會給一些備注來幫助你理解。
變量與常量
創建一個變量
//Objective-CNSInteger score = 556;//NSString *name = @"Taylor";//BOOL loggedIn = NO;
//Swiftvar score = 556//var name = "Taylor"//var loggedIn = false
創建一個常量
//Objective-Cconst NSInteger score = 556;//NSString * const name = @"Taylor";//const BOOL firstRun = YES;//Objective-C中常量用的很少
//Swiftlet score = 556//let name = "Taylor"//let firstRun = true//Swift中常量很常見
創建一個變量數組
創建一個常量數組
//Objective-CNSArray *grades = @[@90, @85, @97];//NSArray *names = @[@"Taylor", @"Adele", @"Justin"];
//Swiftlet grades = [90, 85, 97]//let names = ["Taylor", "Adele", "Justin"]
向數組中添加一個值類型
//Objective-CNSMutableArray *array = [NSMutableArray new];//[array addObject:[NSValue valueWithRect:CGRectMake(0, 0, 32, 64)]];//在添加到集合前,值類型有對應的引用類型
//Swiftvar array = [CGRect]()//array.append(CGRect(x: 0, y: 0, width: 32, height: 64))
創建一個字典
//Objective-CNSDictionary *houseNumbers = @{ @"Paul": @7, @"Jess": @56, @"Peter": @332 };
//Swiftlet houseNumbers = ["Paul": 7, "Jess": 56, "Peter": 332]
定義一個枚舉
//Objective-Ctypedef NS_ENUM(NSInteger, ShapeType) { kCircle, kRectangle, kHexagon};
//Swiftenum ShapeType: Int { case circle case rectangle case hexagon}
附加一串字符
//Objective-CNSString *first = @"Hello, ";NSString *second = [first stringByAppendingString:@" world!"];
//Swiftlet first = "Hello, "let second = first + "world!"
增加數字
//Objective-CNSInteger rating = 4;rating++;rating += 3;
//Swiftvar rating = 4rating += 1rating += 3
插入字符串
//Objective-CNSString *account = @"twostraws";NSString *str = [NSString stringWithFormat:@"Follow me on Twitter: %@", account];
//Swiftlet account = "twostraws"let str = "Follow me on Twitter: /(account)"
打印調試信息
//Objective-CNSString *username = @"twostraws";NSLog(@"Username is %@", username);
//Swiftlet username = "twostraws"print("Username is /(username)")
控制流
檢查狀態
//Objective-CNSInteger result = 86;if (result >= 85) { NSLog(@"You passed the test!");} else { NSLog(@"Please try again.");}
//Swiftlet result = 86if result >= 85 { print("You passed the test!")} else { print("Please try again.")}
循環一定次數
//Objective-Cfor (NSInteger i = 0; i < 100; ++i) { NSLog(@"This will be printed 100 times.");}
//Swiftfor _ in 0 ..< 100 { print("This will be printed 100 times.")}
在數組中循環
//Objective-CNSArray *companies = @[@"Apple", @"Facebook", @"Twitter"];for (NSString *name in companies) { NSLog(@"%@ is a well-known tech company.", name);}
//Swiftlet companies = ["Apple", "Facebook", "Twitter"]for name in companies { print("/(name) is a well-known tech company.")}
數值切換
//Objective-CNSInteger 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有范圍支持,所以你也許看到二選一的語法
//Swiftlet rating = 8switch 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];
//Swiftfunc printGreeting() { print("Hello!")}printGreeting()
不接收參數,返回一個字符串的函數
//Objective-C- (NSString*)printGreeting { return @"Hello!";}NSString *result = [self printGreeting];
//Swiftfunc printGreeting() -> String { return "Hello!"}let result = printGreeting()
接收一個字符串,返回一個字符串的函數
//Objective-C- (NSString*)printGreetingFor:(NSString*)user { return [NSString stringWithFormat:@"Hello, %@!", user];}NSString *result = [self printGreetingFor:@"Paul"];//第一個參數的名稱需要為方法名的一部分
//Swiftfunc 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];
//Swiftfunc 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),所以用字典或數組替代
//Swiftfunc loadAddress() -> (house: String, city: String, country: String) { return ("65, Park Street", "Bristol", "UK")}let (city, street, country) = loadAddress()
不接收參數沒有返回的閉環
//Objective-Cvoid (^printUniversalGreeting)(void) = ^{ NSLog(@"Bah-weep-graaaaagnah wheep nini bong");};printUniversalGreeting();
//Swiftlet universalGreeting = { print("Bah-weep-graaaaagnah wheep nini bong")}universalGreeting()
不接收參數返回一個字符串的閉環
//Objective-CNSString* (^getUniversalGreeting)(void) = ^{ return @"Bah-weep-graaaaagnah wheep nini bong";};NSString *greeting = getUniversalGreeting();NSLog(@"%@", greeting);
//Swiftlet getUniversalGreeting = { return "Bah-weep-graaaaagnah wheep nini bong"}let greeting = getUniversalGreeting()print(greeting)
接收一個字符串參數,返回一個字符串的閉環
//Objective-CNSString* (^getGreeting)(NSString *) = ^(NSString *name) { return [NSString stringWithFormat:@"Live long and prosper, %@.", name];};NSString *greeting = getGreeting(@"Paul");NSLog(@"%@", greeting);
//Swiftlet 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
//Swiftclass MyClass: NSObject {}//推薦使用結構代替類,這樣也許不需要從NSObject繼承了
創建有2個屬性的類
//Objective-C@interface User : NSObject@property (nonatomic, copy) NSString *name;@property (nonatomic, assign) NSInteger age;@end@implementation User@end
//Swiftclass 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實際上并不支持私有屬性,通常都用這種變通方式
//Swiftclass 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
//Swiftclass Civilization { func getMeaningOfLife() -> Int { return 42 }}
創建有一個靜態方法的類
//Objective-C@interface Civilization : NSObject+ (NSInteger)getMeaningOfLife;@end@implementation Civilization+ (NSInteger)getMeaningOfLife { return 42;}@end//差別很小,用+而不是-
//Swiftclass 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
//Swiftextension String { func trimmed() -> String { return trimmingCharacters(in: .whitespacesAndNewlines) }}
檢查一個對象的類
//Objective-Cif ([object isKindOfClass:[YourClass class]]) { NSLog(@"This is a YourClass.");}
//Swiftif object is YourClass { print("This is a YourClass.")}
類型轉換
//Objective-CDog *poodle = (Dog*)animalObject;
//Swiftlet poodle = animalObject as? Dog//let poodle = animalObject as! Dog//如果不是一個dog,前者會把poodle設為nil,后者則會崩潰
GCD
在不同線程運行代碼
//Objective-Cdispatch_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"); });});
//SwiftDispatchQueue.global().async { print("Running in the background...") DispatchQueue.main.async { print("Running on the main thread") }}
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對VEVB武林網的支持。
新聞熱點
疑難解答