Swiftier
许多代码来自 PSPDFKit 关于 Swiftier Objective-C 文章的复制。
import Swiftier;
使用以下代码。
Let 和 Var
现在您可以在编译器可以推理类型的情况下使用 let 和 var 来声明变量的类型。
它们等同于 __auto_type const
和 __auto_type
。如果使用 ObjC++,则相当于 auto const
和 auto
。
用法
let array = @[@1,@2,@3];
var number = 1;
Guard
现在您可以使用 guard
来保护一个特定的条件。 guard (condition)
等同于 if(condition){}
,当条件不满足时以一种更易于理解的方式进行操作,如果你单独调用 guard (condition)
,它将不执行任何操作,您应该使用“swift方式”来保护条件。
guard (condition) else { /* do something else */ }
这等价于 Swift 中的
guard condition else { /* do something else */ }
这在某些条件不满足时需要返回 nil 的情况下是很有用的。
let a = somethingElse;
guard (a != nil) else { return nil; }
[a continueToSomeOtherThings];
安全块
在不进行 null 检查的情况下运行可空块。
safeBlock(block, arguments);
// is equivalent to
if (block) block(arguments);
并且可以通过以下方式在指定线程上安全地运行块:
asyncQueueBlock(queue, block, ...);
mainQueueBlock(block, ...);
安全展开
检查一个潜在的空对象,返回计算出的值,或者如果对象为空,则返回默认值。当对象表示法非常长(在objc中经常发生)且不需要重复输入时,这很有用。
- (void)updateTextToMatchAButton {
self.label.title = safelyUnwrap(self.someView.button.title, defaultTitle);
// instead of
self.label.title = self.someView.button.title ? self.someView.button.title : defaultTitle;
}
内联 foreach
当集合具有类型信息时,我们可以使用
foreach(element, collection) { ... }
基于块的 Foreach, Map, FlatMap, Filter
这些四方法适用于 NSArray
和 NSMutableArray
,它们各自接受一个块,并对内部的每个元素运行该块。
用法
let array = @[@1, @2, @3];
let mappedArray = [array swt_map:^AnotherType(NSNumber *number) {
return [AnotherType initWith:number];
}];
// result -> @[AnotherType(@1), AnotherType(@2), AnotherType(@3)];
let filteredArray = [array swt_filter:^BOOL(NSNumber *number) {
return number.intValue > 2;
}];
// result -> @[@3];
[array swt_forEach:^BOOL(NSNumber *number) {
NSLog(number);
}];
// prints: 1 2 3
let array = @[@1, null, @3];
let mappedArray = [array swt_compactMap:^AnotherType(NSNumber *number) {
return [AnotherType initWith:number];
}];
// result -> @[AnotherType(@1), AnotherType(@3)];
Defer
- (void)foo {
swt_defer { NSLog(@"2") };
NSLog(@"1");
}
// prints ->
// 1
// 2
Safe KeyPath
keyPath(object, path)
来获取编译器检查的关键路径而不是字符串类型的路径。
Infomative Copy
某些集合类型现在在 copy
或 mutableCopy
中具有类型信息。
封装结构体
一些结构体类型,例如CGRect
、CGPoint
等可以封装为NSValue
。
let rect = CGRectMake(1,2,3,4);
let value = @(rect);