通过Swift学习Objective-C:变量、类、方法和属性

学习了一段时间Swift,做了两个小App感觉都还不错。但是由于大量的参考资料、第三方库都用的Objective-C,不学OC语法是不可能的。

根据系列教程Learn Swift From Objective-C整理了一下教程,供先学Swift,再想了解Objective-C语法的小伙伴。

变量和常数

变量定义

Objective-C

1
2
int highScore;
NSString *playerName;

Swift

1
2
var highScore: Int
var playerName: String

变量赋值

Objective-C

1
2
highScore = 1000;
playerName = @"Joe Chan";//Objective-C 给字符串赋值需要带个@

Swift

1
2
highScore = 1000
playerName = "Joe Chan"

常量赋值

Objective-C

1
2
NSString *const skyColor = @"Blue";
int const daysInYear = 365;

Swift

1
2
let skyColor = "Blue"
let daysInYear = 365

定义类

Objective-C中类分需要在两个文件中表示,一个是.h文件一个是.m文件

其中.h文件存放类、函数声明,类声明用关键字@interface
@end来声明,如

1
2
@interface CustomClass : NSObject
@end

.m文件存放类的具体实现,类实现使用关键字@implementation @end来实现,如

1
2
@implementation CustomClass
@end

Swift

1
2
class CustomClass {
}

创建新的类(Creating a new class instance)

Objective-C

1
2
CustomClass *instance = [[CustomClass alloc] init]; //第一次需要用init函数初始化
CustomClass *secondInstance = [CustomClass new];//第二次就不需要init

Swift

1
var instance = CustomClass()

子类

Objective-C

.h函数声明文件(header file)中

1
2
@interface SpecificCar : Car
@end

Swift

1
2
class SpecificCar : Car {
}

方法(Methods)

声明方法

Objective-C的方法跟类一样分需要在两个文件中表示

其中.h文件存放方法声明

1
- (int) getOdometerReading;

.m文件存放方法的具体实现

1
2
3
4
- (int) getOdometerReading
{
return 50000;
}

Swift

1
2
3
func getOdometerReading() -> Int {
return 50000
}

调用方法(函数)

Objective-C

1
2
SpecificCar *myCar = [[SpecificCar alloc] init];//首次调用需要创建并初始化
[myCar getOdometerReading];

Swift

1
2
swiftvar myCar = SpecificCar()
myCar.getOdometerReading()

声明方法(带参数)

Objective-C

1
2
3
- (void)changeEngineOil:(int)oil transmissionFluid:(int)fluid
{
}

Swift

1
2
3
func changeEngineOil(oil:Int, transmissionFluid:Int)
{
}

调用方法(带参数)

Objective-C

1
[myCar changeEngineOil:10 transmissionFluid:10];

Swift

1
myCar.changeEngineOil(10, transmissionFluid:10);

重载(Override

Objective-C

1
2
3
4
5
- (void)someMethod
{
[super someMethod];
// Additional overridden behavior below
}

Swift

1
2
3
4
5
override func someMethod()
{
super.someMethod()
// Additional overridden behavior below
}

属性

声明属性

Objective-C .m文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@interface SpecificCar ()

@property NSString *transmission;
@property int numberOfSeats;

@end

@implementation SpecificCar
- (id)init
{
self = [super init];
if (self)
{
self.transmission = @"Automatic";
self.numberOfSeats = 4;
}
return self;
}
@end

Swift

1
2
3
4
5
6
7
8
9
10
class Specific:Car {
var transmission: String = "Automatic"
var numberOfSeats: Int

init()
{
self.numberOfSeats = 4
super.init()
}
}

Overriding the getter and setter

Objective-C

1
2
3
4
5
6
7
8
9
- (void)setTransmission:(NSString *)transmission
{
_transmission = transmission;
}

- (NSString *)transmission
{
return _transmission;
}

Swift

1
2
3
4
5
6
7
8
var transmission: String {
get {
return _transmission
}
set {
_transmission = newValue
}
}

下一篇

参考