当做自己学习的字典,以后经常补充和完善
变量和常量
创建一个变量
//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
NSMutableArray *grades = [NSMutableArray array];
NSMutableArray<SQModel *> *SQArray =[NSMutableArray array];
//Swift
var array = [String]()//用这个比较好
var array = Array<String>()
创建一个常量数组
//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)]];
//在添加到集合前,值类型有对应的引用类型
//Objective-C
//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
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继承了
创建常见类
//Objective-C
@interface User : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSInteger age;
- (NSInteger)getMeaningOfLife;
+ (NSInteger)getMeaningOfLife;
@end
@implementation User
- (NSInteger)getMeaningOfLife {
return 42;
}
+ (NSInteger)getMeaningOfLife {
return 42;
}
@end
//OC私有属性在.m文件中
//Swift
class User {
var name: String?
var age: Int?
private var age: Int?//私有属性
//实例方法
func getMeaningOfLife() -> Int {
return 42
}
//Swift也支持静态方法——它不会在子类中被覆盖
class func getMeaningOfLife() -> Int {
return 42
}
}
检查一个对象的类
//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,后者则会崩溃
线程
//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")
}
}
借鉴文章地址
网友评论