一、懒加载
- Objective-C
@interface ViewController ()
@property(nonatomic, strong) NSArray *dataArray;
@end
@implementation ViewController
- (NSArray *)dataArray {
if (!_dataArray) {
_dataArray = @[@"data1",@"data2",@"data3"];
}
return _dataArray;
}
@end
- Swift
lazy var dataArray: [String] = {
let array = ["data1","data2","data3"]
return array
}()
二、单例
- Objective-C
@implementation Manager
+ (instancetype)sharedManager {
static Manager * sharedManager;
static dispatch_once_t predicate;
dispatch_once(&predicate, ^{
sharedManager = [[Manager alloc] init];
});
return sharedManager;
}
@end
- Swift
class Manager: NSObject {
static let manager = Manager()
}
三、getter和setter
- Objective-C
@interface ViewController ()
@property (nonatomic, copy) NSString *name;
@end
@implementation ViewController
@synthesize name = _name;
/// 同时重写setter和getter时需要synthesize
- (void)setName:(NSString *)name {
if (_name != name) {
[_name release];
_name = [name copy];
}
_name = name;
}
- (NSString *)name {
return _name;
}
- Swift
// swift一般不重写getter和setter方法,一般都是些willSet或者didSet
var name: String? {
willSet {
self.name = newValue
}
didSet {
print(self.name)
}
}
四、冒泡排序
- Objective-C
NSMutableArray * array = [@[@100, @120, @50, @10, @40, @60, @1] mutableCopy];
NSLog(@"%@",[self bubblingSortWithArray:array]);
- (NSArray *)bubblingSortWithArray:(NSMutableArray *)array {
for (int i = 0; i < array.count; i ++) {
for (int j = 0; j < array.count - 1 - i; j ++) {
if (array[j] > array[j + 1]) {
[array exchangeObjectAtIndex:j withObjectAtIndex:j + 1];
}
}
}
return array;
}
- Swift
var array = [100, 120, 50, 10, 40, 60, 1]
print(bubblingSort(array: &array))
func bubblingSort(array: inout [Int]) -> [Int] {
for i in 0..<array.count {
for j in 0..<array.count - i - 1 {
if array[j] > array[j + 1] {
array.swapAt(j, j + 1)
}
}
}
return array
}
网友评论