c_cpp 与Obj-C“generics”的乐趣

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 与Obj-C“generics”的乐趣相关的知识,希望对你有一定的参考价值。

@import Foundation;
#import "Function.h"

int main(int argc, const char * argv[])
{
    @autoreleasepool {
        
        Function<NSString *, NSArray<NSString *> *> *stringSplitter = [[Function alloc] initWithBlock:^(NSString *str) {
            return [str componentsSeparatedByString:@","];
        }];
        
        // works (unspecified)
        NSArray *__unused result0 = [stringSplitter evaluateAt:@"hello,there"];
        
        // works (all NSStrings are NSObjects)
        NSArray<NSObject *> *__unused result1 = [stringSplitter evaluateAt:@"hello,there"];
        
        // warning: incompatible pointer types ... (not all NSStrings are NSMutableStrings)
        NSArray<NSMutableString *> *__unused result2 = [stringSplitter evaluateAt:@"hello,there"];
        
        // works (all NSMutableStrings are NSStrings)
        Function<NSMutableString *, NSArray<NSObject *> *> *__unused mutableStringSplitter = stringSplitter;
        
        // warning: incompatible pointer types ... (not all NSObjects are NSStrings)
        Function<NSObject *, NSArray<NSString *> *> *__unused arbitrarySplitter = stringSplitter;
        
        // warning: incompatible pointer types ... (not all NSStrings are NSMutableStrings)
        Function<NSString *, NSArray<NSMutableString *> *> *__unused stringSplitterToMutable = stringSplitter;
    }
    return 0;
}
// Unfortunately, the generated Swift interface is not very useful:

import Foundation

class Function : NSObject {
    
    init(block: (AnyObject) -> AnyObject)
    
    func evaluateAt(value: AnyObject) -> AnyObject
}
@import Foundation;


NS_ASSUME_NONNULL_BEGIN

@interface Function<__contravariant InType, __covariant OutType> : NSObject
{
    // interestingly, this does work here (though OutType & InType are not available in the @implementation)
    OutType (^_block)(InType);
}

- (instancetype)initWithBlock:(OutType (^)(InType))block;

- (OutType)evaluateAt:(InType)value;

@end

NS_ASSUME_NONNULL_END

以上是关于c_cpp 与Obj-C“generics”的乐趣的主要内容,如果未能解决你的问题,请参考以下文章

我的 react js 代码如何与现有的 Obj-C 逻辑交互?

Obj-C 语言学习 笔记(II)类定义与实现

如何将 Obj-C 中的 UITouch 对象与 WebKit JavaScript 中的相应触摸对象匹配?

Kotlin基础知识九: Generics

iOS:在 UIWebview 中使用 javascript 调用 obj-c 方法

[Obj-C笔记] "self = [super init]"的解释与潜藏bug