Conversion Quick Search Manual for OC and Swift Requirements for iOS Development (strongly recommended)

Keywords: Mobile Swift

This article mainly introduces the relevant information about Objective-C and Swift's Handbook of quick search for conversion. The sample code is introduced in detail in this article. It is highly recommended for your reference and learning. It invites readers to join the small group exchange group: 624212887, to exchange and learn together.

Preface

If you are moving from Objective-C to Swift, or vice versa, a brochure showing equivalent code between two languages will be helpful. That's what this article is about: Apple developer's Red Treasure Book, which includes variables, collections, functions, classes, and so on.

In the following example, above is the Objective-C code, and below is the equivalent Swift code. Where necessary, I'll give you some notes to help you understand.

Variables and Constants

Create a variable

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

Create a constant

//Objective-C
const NSInteger score = 556;
//
NSString * const name = @"Taylor";
//
const BOOL firstRun = YES;
//Object-C is rarely used
//Swift
let score = 556
//
let name = "Taylor"
//
let firstRun = true
//Swift constants are common

Create an array of variables

Create a constant array

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

Add a value type to the array

//Objective-C
NSMutableArray *array = [NSMutableArray new];
//
[array addObject:[NSValue valueWithRect:CGRectMake(0, 0, 32, 64)]];
//Before adding to a collection, the value type has a corresponding reference type
//Swift
var array = [CGRect]()
//
array.append(CGRect(x: 0, y: 0, width: 32, height: 64))

Create a dictionary

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

Define an enumeration

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

Attach a string of characters

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

add number

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

Insert string

//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)"

Print debugging information

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

control flow

Check state

//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.")
}

Cycle a certain number of times

//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.")
}

Loop in an array

//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.")
}

Numerical switching

//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.");
}
//Many people don't know that Objective-C has scope support, so you may see a grammar of two choices.
//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 won't fall through the case unless you use the fall through keyword

function

Functions that do not receive parameters and do not return

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

Returns a function of a string without receiving parameters

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

Receive a string and return a function of a string

//Objective-C
- (NSString*)printGreetingFor:(NSString*)user {
 return [NSString stringWithFormat:@"Hello, %@!", user];
}
 
NSString *result = [self printGreetingFor:@"Paul"];
//The name of the first parameter needs to be part of the method name
//Swift
func printGreeting(for user: String) -> String {
 return "Hello, \(user)!"
}

let result = printGreeting(for: "Paul")

Receive a string and an integer and return a function of a string

//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)

Returns multiple values from a function

//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"];
//Object-C does not support tuple, so use dictionaries or arrays instead.
//Swift
func loadAddress() -> (house: String, city: String, country: String) {
 return ("65, Park Street", "Bristol", "UK")
}
 
let (city, street, country) = loadAddress()

Closed Loop without Receiving Parameters and Not Returning

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

Closed loop that returns a string without receiving parameters

/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)

Receive a string parameter and return a closed loop of a string

//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)

class

Create empty class

//Objective-C
@interface MyClass : NSObject
@end
 
@implementation MyClass
@end
//Swift
class MyClass: NSObject {
}
//Structures are recommended instead of classes, so you may not need to inherit from NSObject

Create a class with two attributes

//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 requires initialization and default values for these properties

Create a class with a private property

//Objective-C
//In the header file
@interface User : NSObject
@property (nonatomic, copy) NSString *name;
@end
 
//Execution Documents
@interface User()
@property (nonatomic, assign) NSInteger age;
@end
 
@implementation User
 
@end
//Objective-C does not actually support private attributes, usually in this flexible way
//Swift
class User {
 var name: String
 private var age: Int
  
 init(name: String, age: Int) {
  self.name = name
  self.age = age
 }
}

Create a class with an instance method

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

Create a class with a static method

//Objective-C
@interface Civilization : NSObject
+ (NSInteger)getMeaningOfLife;
@end
 
@implementation Civilization
+ (NSInteger)getMeaningOfLife {
 return 42;
}
@end
//The difference is very small. Use + instead of -
//Swift
class Civilization {
 class func getMeaningOfLife() -> Int {
  return 42
 }
}
//Swift also supports static methods -- it won't be overridden in subclasses

Extending a type in a new way

//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)
 }
}

Check the class of an object

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

Type conversion

//Objective-C
Dog *poodle = (Dog*)animalObject;
//Swift
let poodle = animalObject as? Dog
//
let poodle = animalObject as! Dog
//If it's not a dog, the former sets poodle to nil, and the latter crashes.

GCD
Running code in different threads

//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")
 }
}

Above is the whole content of this article, I hope the content of this article has some reference value for learning big furniture. If you have any questions, you can enter the small group exchange group: 624212887, exchange and study together. Thank you for your support.

Posted by NoBullMan on Sun, 20 Jan 2019 14:12:12 -0800