這篇文章主要給大家介紹了關於Objective-C和Swift的轉換速查手冊的相關資料,文中通過示例程式碼介紹的非常詳細,非常推薦給大家參考學習使用,盛情邀請讀者進入小編交流群:624212887,一起交流學習

前言

如果你正要從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中常量用的很少
//Swift
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")
 }
}

以上就是這篇文章的全部內容了,希望本文的內容對大傢俱有一定的參考學習價值,如果有疑問大家可以進入小編交流群:624212887,一起交流學習,謝謝大家的支援