03. Property Defaults and Initialization Constructors

It will take about 1 minutes to finish reading this article.

We often use the following methods to initialize in OC.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// OCDemoModelBuilder.h
@interface OCDemoModelBuilder : NSObject
@property (nonatomic, copy, nonnull) NSString *a;
@property (nonatomic, copy, nonnull) NSString *b;
@property (nonatomic, copy, nonnull) NSString *c;
@property (nonatomic, copy, nonnull) NSString *d;
@property (nonatomic, copy, nonnull) NSString *e;
@end
// OCDemoModelBuilder.m
@implementation OCDemoModelBuilder

- (instancetype)init {
if (self = [super init]) {
_a = @"a";
_b = @"b";
_c = @"c";
_d = @"d";
_e = @"e";
}
return self;
}

@end

// OCDemoModel.h
@interface OCDemoModel : NSObject
@property (nonatomic, readonly, nonnull) NSString *a;
@property (nonatomic, readonly, nonnull) NSString *b;
@property (nonatomic, readonly, nonnull) NSString *c;
@property (nonatomic, readonly, nonnull) NSString *d;
@property (nonatomic, readonly, nonnull) NSString *e;

- (instancetype)initWithBuilder:(void(^)(OCDemoModelBuilder *builder))builderBlock;
@end

// OCDemoModel.m
@implementation OCDemoModel
- (instancetype)initWithBuilder:(void(^)(OCDemoModelBuilder *builder))builderBlock {
if (self = [super init]) {
OCDemoModelBuilder *builder = [[OCDemoModelBuilder alloc] init];
if (builderBlock) {
builderBlock(builder);
}
_a = builder.a;
_b = builder.b;
_c = builder.c;
_d = builder.d;
_e = builder.e;
}
return self;
}

@end

// Usage
OCDemoModel *ret = [[OCDemoModel alloc] initWithBuilder:^(OCDemoModelBuilder * _Nonnull builder) {
builder.b = @"b1";
}];

However, Swift’s Struct supports attribute default values and initialization constructors, which greatly simplifies the process. The code is as follows:

1
2
3
4
5
6
7
8
9
10
11
struct SwiftDemoModel {
var a = "a"
var b = "b"
var c = "c"
var d = "d"
var e = "e"
}

// Usage
let ret = SwiftDemoModel(b: "b1")
// ret = a,b1,c,d,e