流亡者 0.7.4

流亡者 0.7.4

测试已测试
Lang语言 Obj-CObjective C
许可证 MIT
发布上次发布2014年12月

Dustin Bachrach维护。



流亡者 0.7.4

这是什么?

流亡者是一个简单的库,为Objective-C添加了as语言构造。

NSObject* obj = /* get an object */;

obj.as(^(id<Drawable> drawable) {
    [drawable draw];
});

在不使用流亡者的情况下,通常的做法是

NSObject* obj = /* get an object */;

if ([obj conformsToProtocol:@protocol(Drawable)]) {
    [(id<Drawable>)obj draw];
}

这很啰嗦,重复,并且编译器也没有检查您是否将转换为相同的协议进行检查。

流亡者使您能够轻松编写简洁且声明性的安全代码。

流亡者还包括一个match构造,用于编写适用于多个情况的安全类型依赖代码。

id result = /* get a result */;

result.match(@[
    ^(NSArray* manyThings) {
        for (id thing in manyThings) { /* ... */ }
    },
    ^(NSString* str) {
        NSLog(@"The string: %@", str);
    },
    ^(UIView* view) {
        [view removeFromSuperview];
    },
    ^(id somethingElse) {
        NSLog(@"wasn't expecting: %@", somethingElse);
    }
]);

match构造返回匹配的执行的代码块的结果。

NSString* description = obj.match(@[
    ^(NSArray* manyThings) {
        return [NSString stringWithFormat:@"%d things", manyThings.count];
    },
    ^(NSString* str) {
        return @"one string";
    },
    ^(id somethingElse) {
        return @"one random thing";
    }
]);

如果obj是一个包含3个元素的NSArray,则description"3 things"。如果obj是一个字符串,则是"one string"。否则是"one random thing"

安装

然后,您只需要导入流亡者头文件

#import <castaway/castaway.h>

id类型上调用as

在上面的例子中,我们使用了带有点符号的asmatch。您不能在id类型的变量上使用属性符号,因此应使用asmatch的消息版本。

id obj = /* get an object */;

[obj as:^(id<Drawable> drawable) {
    [drawable draw];
}]; 

作者

Dustin Bachrach,[email protected]

特别感谢PromiseKitMax Howell,感谢NSMethodSignatureForBlock

许可证

流亡者可在MIT许可证下使用。有关更多信息,请参阅LICENSE文件。